Calculate screen size in a sticky header - javascript

There are tonnes of tutorials / examples of making a header stick on scroll for fixed height headers. However, I am working on a one page website and the initial section is a full screen image. The user then scrolls down to reveal the header and other content areas.
So my question is, how can I change my code to take into account the viewport / screen size - rather than use a fixed header size?
My existing code is:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 65) {
$(".main").addClass("sticky");
} else {
$(".main").removeClass("sticky");
}
});

You could use the height of the window instead of a fixed value (since you're talking about a full screen image, I'm guessing its height is equal to the window height):
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= $(window).height()) {
$(".main").addClass("sticky");
} else {
$(".main").removeClass("sticky");
}
});
You could also get the height of the first section, if it's smaller than the window

I don't know if there's a better solution, but here's my solution :
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= $(window).height()*0.2) { //0.2 for 20% of the viewport height, you can change this value if you need to
$(".main").addClass("sticky");
} else {
$(".main").removeClass("sticky");
}
});
I just used $(window).height() to get the viewport height.

Related

Fix on scroll but with varying screen size no set pixel distance

I have a div with an image background thats height is 100% so it fills the screen on any device. At the bottom of the screen is then a navigation bar. When the page is scrolled I want the navigation bar to fix to the top of the screen at a set distance away from the top.
I have tried using this JavaScript:
$(window).scroll(function(){
if ($(this).scrollTop() > 587) {
$('.hnav').addClass('hfixed');
} else {
$('.hnav').removeClass('hfixed');
}});
It works fine on my screen but on any other screen it doesn't because the navigation changes distance from the top depending on the window size because of the 100% height image.
How can I get the navigation to fix in place when its a set distance from the top regardless of the window size??
Thanks
You can get the element's position with element.getBoundingClientRect(), so you can add the 'hfixed' class once this returns a top value of 0:
var nav = $('.hnav');
var pos = nav.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos + 50 >= pos.top) {
nav.addClass("hfixed");
} else {
nav.removeClass("hfixed");
}
});
EDIT:
Added an extra margin of 50px to the calc, because the top bar.
EDIT 2:
Changed the example, now it's based on this
EDIT 3:
Add the 50px margin because the top bar to the new example

Scrolling Two Divs Using JQuery/Javascript

Wrapper - Overflow Hidden
Div One: Sidebar
Div Two: Main Content
Div Two will have a normal scroll. Div One I wish to have no visible scroll however when you scroll Div One it scrolls Div Two.
Upon Div One's height hitting the bottom, it will no longer scroll and visa-versa for scrolling back up.
This will result in the sidebar always being visible at the side. Before you ask, I've tried all positioning types to get this to work resulting in many failed attempts.
My live demo can be seen here: http://rafflebananza.com/admin/newadmin.html#
Note I've tried to make a JSFiddle simplified but my maths does not seem to work in there the same. Please suggest whether I should fork all my page to there or whatnot for future visitors needing the same help.
Overview
Scrolling in the wrapper will scroll sidebar to point x only (x being the sidebars height) then stopping but will continue to allow the content to be scrolled. Visa-versa for scrolling back up.
Somewhat half way there...
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop,
position = document.body.scrollTop;
function scrollD() {
var scroll = document.body.scrollTop;
if (scroll > position) {
// Scrolling Down Functions
} else {
// Scrolling Up Functions
}
position = scroll;
}
Updated the answer to match OPs requirements.
I downloaded your website in its current state and made the following changes to your code:
var scrollY = 0;
$(window).scroll(function() {
var sideNav = $('.SideNav'); // The side navigation
var wScrollY = $(this).scrollTop(); // Current scroll position of Window
var navHeight = sideNav.height(); // Height of the Navigation
var StageHeight = $(window).height() - 46; // The display space
if(sideNav.height() > StageHeight) { // Do the following if the side navigation is higher than the display space
var spaceLeft = sideNav.height() - StageHeight; // spaceLeft -> how many pixel left before fixing navigation when scrolling
if(scrollY < wScrollY) { // Scroll direction is down
if (wScrollY >= spaceLeft) // If scroll top > space left -> fixate navigation at the bottom, otherwise scroll with the content
sideNav.css({top:46-spaceLeft+wScrollY});
if (wScrollY <= 46) // Set top strict to 46. Sometimes there is white space left, caused by the scroll event.
sideNav.css({top:46});
} else { // Scroll direction is up
var sideNavTop;
if (sideNav.offset().top < 0) {
sideNavTop = Math.pow(sideNav.offset().top); // if top is negative, make it positive for comparison
} else {
sideNavTop = sideNav.offset().top;
}
if (sideNavTop > (46+wScrollY)) // Fixate the header if top of navigation appears
sideNav.css({top:46+wScrollY});
}
} else {
sideNav.css({top:46+wScrollY}); // Fixate always
}
scrollY = wScrollY;
});
This will let you scroll your side navigation up until its end. Then fixate. If you scroll up, it will still be fixated until your reach the point, where the navigation must scrolled back to its original position.
You can check the edited version here: http://pastebin.com/Zkx4pSKe
Just copy the raw code into a blank html page and try it out.
It's a bit messy and maybe not the best solution, but it works.
Ok, here you go:
var $sidebar = $('.sidebar'),
$window = $(window),
previousScroll = 0;
$window.on('scroll', function (e) {
if ($window.scrollTop() - previousScroll > 0) {
$sidebar.css({
'top': Math.max($window.scrollTop() + $window.height() - $sidebar.outerHeight(true), parseInt($sidebar.css('top'))) + 'px'
});
} else {
$sidebar.css({
'top': Math.min($window.scrollTop(), parseInt($sidebar.css('top'))) + 'px'
});
}
previousScroll = $window.scrollTop();
});
http://jsfiddle.net/7nwzcpqk/1/
i might have misunderstood your desired result incorrectly but you can see if this works for you :
.SideNav {
position: fixed; // you currently have this as position:absolute;
}
You don't need nor a wrapper element nor jQuery. I assume that you are using a wrapper because you want to have the top bar placed there. I think there is a better way to do it by using simply three divs.
The top bar has to be fixed (to be always visible) and of full width.
The side bar also has to be fixed (to be always visible) with a top margin of the height of the top bar.
The content needs just a left padding (width of side bar) and top padding (height of top bar).
Here is the example code (http://jsfiddle.net/zckfwL4p/):
HTML
<div id="top_bar"></div>
<div id="side_bar">links here</div>
<div id="content"></div>
CSS
body {
margin:0px;
padding:0px;
}
#side_bar {
width:50px;
position: fixed;
left:0px;
top:20px;
background-color:blue;
}
#top_bar {
position:fixed;
height:20px;
left:0px;
right:0px;
background-color:red;
}
#content {
position:relative;
padding-left:55px;
padding-top:25px;
}

Sidebar jumps uncontrollably when the height is modified on scroll

I have a sidebar on my site that is fixed to the side and when the user scrolls down or up, the style attribute top is changed so that the height is adjusted.
$(window).scroll(function() {
if ($(this).scrollTop() < 125){
var v = 125 - $(this).scrollTop();
$("#sidebar").css({'top':v + 'px'});
}
if ($(this).scrollTop() >= 125)
{
$("#sidebar").css({'top':'5px'});
}
});
However, when I scroll down, the sidebar seems to jump uncontrollably and does not stick to the screen as I would like. I am using Chrome 32 so I don't see what the problem is. Please can someone help me with this issue.
Check out this fiddle.
Create a CSS class called fixed.
.fixed {
position: fixed;
top: 0px;
}
On scroll, in your JavaScript add and remove the "fixed" class accordingly to make the proper effect.
JavaScript:
$(function () {
var $sidebar = $('#sidebar');
$(window).on('scroll', function () {
if($(this).scrollTop() < 125) {
$sidebar.removeClass('fixed');
} else {
$sidebar.addClass('fixed');
}
});
});
As the header scrolls out of the window, the sidebar gets the "fixed" class and sticks to the side of the screen at the top left (0,0) respectively. When the header is coming back into view, the class is removed and the sidebar moves gracefully back to it's original position.

jQuery fixed sidebar that moves with content if overflow

I have the following fiddle: http://jsfiddle.net/yFjtt/1/
The idea is that the user can scroll PAST the header to make the sidebar 'stick' in place while they scroll further down the page.
As they near the bottom of the page it should then work out how much space is left and how much space the sidebar needs and the add some negative margin to move the sidebar upwards whilst maintaining the fixed position.
Upto here it all works fine.
The next problem is making sure that the sidebar only moves up as far as it needs to and should remain about 10 pixels from the bottom. This way the sidebar will be fixed until it needs to move upward to reveal its content and then once it's all shown become stuck again about 10 pixels from the bottom.
Here is where I have tried to achieve this (see fiddle for full code):
if( $(window).scrollTop() > (documentHeight - sidebarHeight) ) {
if( offsetBottom < 10) {
}
else {
$('div.sidebar').stop(true,false);
$('div.sidebar').animate({'margin-top':offset}, 300);
}
} else {
$('div.sidebar').stop(true,true);
$('div.sidebar').css({'margin-top':'0'});
}
However the sidebar STILL moves too far up the page... Can anyone help? I'm sure it's just a simple mistake working out the offset from the bottom.
I think you had a good try, except I'm not sure what those animations are doing there. Basically you need 3 checks, first to see if the use is above the header, second to check if they're between the header and the bottom most limit for the sidebar, and lastly if they're below that point. Then simply swap and change classes and modify top value as necessary.
jsFiddle
var sidebarHeight = $('div.sidebar').height();
var documentHeight = $(document).height();
var headerHeight = $('div.header').height();
$(window).scroll(function() {
var margin = 10;
var sidebar_offset = documentHeight - sidebarHeight - (margin * 2); // double margin to account for top and bottom margins
if ($(window).scrollTop() > headerHeight && $(window).scrollTop() < sidebar_offset ) {
// below header, but above the sidebar offset limit
$('div.sidebar').addClass('fixed');
$('div.sidebar').css('top', '');
}
else if ( $(window).scrollTop() <= headerHeight ) {
// above header
$('div.sidebar').removeClass('fixed');
$('div.sidebar').css('top', '');
}
else {
// past the sidebar offset limit
$('div.sidebar').removeClass('fixed');
$('div.sidebar').css('top', documentHeight - sidebarHeight - margin);
}
});​

Dynamic Image Resizing

I have an image on a webpage that needs to be stretched to fit the available space in the window whilst maintaining its proportion. Here's what I've got:
http://www.lammypictures.com/test/
I would like the large image to proportionally stretch to match the height and widths of the browser, minus the size of the divs to the left and bottom.
So the problem is 2 fold really; first i need to get the max height and width minus the link and image bars, secondly i need to resize the image on a browser resize whilst maintaining proportions.
Any help would be much appreciated.
Cheers
CIP
You could try using jQuery ui scaling effect:
$(document).ready(function () {
resizeImage(); // initialize
$(window).resize(function () {
resizeImage(); // initialize again when the window changes
});
function resizeImage() {
var windowHeight = $(window).height() - $('#nav').height(),
windowWidth = $(window).width(),
percentage = 0;
if (windowHeight >= windowWidth) {
percentage = (windowWidth / $('#image').width() ) * 100;
}
else {
percentage = ( windowHeight / $('#image').height() ) * 100;
}
$('#image').effect('scale', { percent : percentage }, 1);
};
});
Tested and works great, however, a few tweaks maybe needed to get it just the way you like it.
You may just not setup the image element width and height attributes, and write next styles:
.hentry img { max-width: 100%; }
And it will shrink relative to the minimum side.
P.S. But not in position: absolute; block which not have any size. Set up the parent block to relative positioning.

Categories

Resources