Have put together a sticky navbar (jsfiddle) that comes into view only after the user scrolls down 10px from the top of the document. However as seen in the fiddle; using:
$(window).scroll(function () {
if ($(this).scrollTop() > 10) {
document.getElementById('navig').style.visibility = 'visible';
this only works in the first instance after the code is run. In subsequent similar actions (after scrolling down the document completely and scrolling back up again) in the same session, the navbar comes into appearance much further down than 10px. It only works again on refresh (rereun) and that too again, only the first instance of top to bottom scrolling.
Also, I'd want the effect to act on scrolling back up ie. the fixed navbar should become absolute at the base of the header when the user moves past that point. And it should hide when scrolling past 10px from top. There isn't a scrollBottom() function, so how is this handled?
This fiddle has jquery loaded: https://jsfiddle.net/6ss64s7e/
How can these issues be addressed? (pardon, am new to javascript).
Before you return to the value position:absolute; you have to delete all the other properties that you added because they won't be automatically deleted - so, you don't need top:0; anymore.
You can delete the top:0; property by passing empty string to its value, like this:
$('#navig').css({'position':'absolute','top':''});
For the detection of scroll and its direction, see this question.
Related
My page has a sticky navbar whose 'stickiness' works fine, however the behaviour of the 2 main internal elements* of the navbar aren't seguing. The 2 main internal elements are the logo and the slide-out navbar(activated on click). The intended behaviour is as follows:
The logo(at center of orange bar) must 'hide' by default and only
become visible when the user scrolls down 80px from the top (or
scrolls upto 80px from the top) of the document.
The logo must hide as soon the user scrolls within 80px of the top of
the document.
The logo must, however, never be visible at the same time the slide-out navbar is active.; the moment the navbar is inactive however, it must become visible again.
Unlike the logo, the navbar icon must always always be visible, and
like the logo, it must be sticky.
In the jsfiddle, all of the intended behaviour plays out, but only on scroll, not on click. ie. After scrolling down more than 80px, the logo will be visible (which is fine), but does not hide when the navbar icon is clicked to the active state (unless the nav element was already in the active state). This issue is resolved the moment I scroll, but not at the moment of click which is what I want happening.
I know why this happening, it's because while I've taken care of all these conditions in $(window).scroll(function (), I haven't in the $("#menu-opener").click(function() simply because I couldn't use scrollTop() there, neither could I successfully combine the two functions.
How then, can I resolve this issue, whether through combining the functions, calling scrollTop() in the clickfunction, or anything else? Would appreciate any help.
Pls note: while I say '2 main internal elements of the navbar', in fact I've placed the logo and slide-out navbar in seperate divs and would like it to remain that way
So why couldn't you use scrollTop there ?
isn't this the expected behaviour:
https://jsfiddle.net/91gxLvbb/4/
You can check the scrolltop with:
if($(window).scrollTop() > 80)
https://jsfiddle.net/91gxLvbb/6/
I added #menulogo:
$("#menu-opener").click(function(){
$("#menu-opener, #menu-opener-inner, #menu, #menulogo").toggleClass("active");
});
And to the css:
#menulogo.active #logoflag{display:none}
I tried to do a minimal version of the problem i am having. In short i am doing header with navigation that always sticks to the top of page when scrolling.
Now the problem is if you try and click on a section in the navigation, when you get scrolled to the section the navigation blocks half the content at the top by getting in the way.
This means the user has to scroll back up a little to see the content properly. I am using lorem ipsum as content replacement there.
How would i adjust where my browser position lands when the user clicks the navigation button so i can position the window correctly?
https://jsbin.com/hopiqe/edit?html,css
Eli-
Using HTML/CSS only, you'd have to do a hack like Kommodore suggests to get this working properly. Your really need JS to do this right.
You can do this with jQuery and a little foresight:
// Button 1 is what you click to start the interaction
$(".button1").click(function() {
// Using jQuery Animate and ScrollTop...
$('html, body').animate({
// We point user to div1
// We have an offset from the top of the window minus 50px
// `-50` should match the height of your header
scrollTop: $("#div1").offset().top-50
// 500 is milliseconds to do the `Animate` interaction
}, 500);
});
You could also use a combination of jQuery plugins called ScrollTo and LocalScroll.
I wired up a working CodePen that builds off the code you provided. The JS probably needs more tightening but you should get the idea.
The easiest way should be adding another div as a placeholder with height: 140px in front of each div (which then has to be called instead of the div) or using margin-top: 140px for each div.
I'm new to jQuery and watching a tutorial for a sticky nav bar and something went wrong and idk what to do!
In my Script file I have it so it runs this code on load [http://pastebin.com/XYWR5tKJ][1] and I have a class in css to use with the nav Placeholder wrap.
Well the margin property doesn't seem to be working, if you run the site and scroll the whole way down the nav bar sticks to the side, its supposed to be centered(the margins job). I have no idea why its not doing it, its probably something stupid but please help!`
HERES THE CODE__
Script.js: http://pastebin.com/XYWR5tKJ
Css: http://pastebin.com/Y51rYJVE
HTML: http://pastebin.com/tTftEJKh
__
THANKS!
[1]: http://pastebin.com/tTftEJKh
Basic set up for a fixed, centered element is:
Containing element that is position fixed.
An element within that has margin:0 auto; and a set width.
I'd say that your left:0 inside fixed is counteracting things mostly.
Since you didn't specify responsive is this good enough for you?
http://jsbin.com/nevuqi/4/
Also probably better, as a tip to share code in something like a JSFiddle, Codepen or JSBin to name a few... good for learning inside of too.
This question reminded me of a JSFIDLE I made a while back to learn the same concept. I've updated it with comments to make it more readable...
It doesn't really answer your question but I thought it would help understand the various components involved when implementing the sticky nav effect in JQuery for anyone who comes across this thread who is unsure.
JavaScript/JQuery code:
(refer to jsfiddle for the accompanying html/css )
//window - the container that holds and renders the document.
//document - the rendered html within the window. the document can be bigger than the window as with this example as scrolling is needed..
//refer to css for more info on the appended classes to nav bar and proceeding element.
$(document).ready(function () {
//add a scroll function to the document that
$(document).on('scroll', function () {
//get the number of pixels that the window is from the top of the document. this is zero at first.
var scrollTop = $(this).scrollTop();
//insert the name of your sticky nav element here in place of .scrollFixed
$('.scrollFixed').each(function () {
//scrollFix variable is initialized as .scrollFixed object with all its attributes.
var scrollFix = $(this);
//gets offset of sticky nav element in pixels
var topDistance = scrollFix.offset().top;
var previousElement = scrollFix.prev();
//this is just for debugging and learning purposes.
$('.fixed_info').html('nav bar is ' + topDistance + ' pixels from top of document');
//if you put topDistance here instead of the number manually, the nav bar will flicker.
//unsure why..
//checks to see whether nav element has been scrolled past the top of window.
if ((298) < scrollTop) {
//make sticky nav a fixed element
scrollFix.addClass("stuck");
//extend the element below for this example so proceeding elements don't visually jump up
//when closing the empty gap.
$(".element_below_fixed_nav_bar").addClass("extend");
//indicates element is fixed!
scrollFix.html("Element now fixed!");
//you will have to manually put the topDistance here as well...
//this checks whether the nav element's original top has passed the top of
//the enclosing window.
//it needs to become scrollable again
} else if (298 >= scrollTop && scrollFix.hasClass('stuck')) {
//make sticky nav a scrollable element
scrollFix.removeClass('stuck');
//make proceeding element shorter to compensate for sticky nav pushing elements below it down.
$(".element_below_fixed_nav_bar").removeClass("extend");
//indicates element is scrollable!
scrollFix.html("Element now moveable!");
}
});
});
});
It's very similar to the logic behind the JavaScript code you linked.
find number of pixels of window from top of document. starts at 0 when document first loads unless otherwise coded. This updates every time you scroll.
find (offset) number of pixels of nav bar element from top of document.
check if nav bar has reached the top of the window by checking its offset to the window. If it is then make it fixed.
check whether the nav bar's original offset has fallen below the top of the window. If it has then make the nav bar scrollable.
It doesn't really answer your question but I thought it would help understand the various components involved when implementing the sticky nav effect in JQuery for anyone who comes across this thread who is unsure.
I'll try to explain a big problem that has me stumped.
Basically, I have a #menu that goes between absolute positioned(when close to the top of the page) and fixed positioned(to the top of the window, when scrolling down the page). I'm using jquery to accomplish this.
When it gets fixed, I give it a ".fixed" class. Which gives it "top:0px;position:relative;". #menu has a transition to it, but #menu.fixed removes the transition. This works great in the beginning, when scrolling down and then having it become attached to the top of the window. Switching the positions is flawless as the new class has the transitions removed.
However, when I scroll back up, and it removes the ".fixed" class, it animates the (now) absolutely positioned #menu from 0px to 615px. Which means it jumps up to the top of the page, and then scrolls down, as it's not fixed anymore.
This is the code:
$('#menu').css({ top: '615px'}); // top was 0px before this. It is still fixed, so it should NOT animated.
$('#menu').removeClass('fixed'); // Now the transition kicks in
//As it's at 615px, it should stay where it is, not start animating to 615px from 0px as it does.
I think it's because the element hasn't actually been repositioned by the time the ".fixed" class is removed, and thus it animates down with it's new positioning... I could do an interval or something similar to trigger the class to be removed, but it just seems silly.
I'm also aware that I could just make it positioned:absolutely all the time. And just reposition the top-value when I scroll. But that seems redundant...
Does anyone know how to solve my problem?
I'd like to set up a "backward-compatible" scrolling sidebar on one of my pages.
I have a page containing information about a species of fish which can be extraordinarily long and images to accompany it.
The images are in the right-hand pane at the moment and I'd like them to follow the user as they scroll to the bottom of the page.
I've used the following code with some success:
jQuery().ready(function($) {
var $scrollingDiv = $("#sidebar");
$(window).scroll(function(){
$scrollingDiv
.stop()
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
});
});
But it jumps too far when scrolling down.
(original position)
(scrolled a single mousewheel click)
When you start scrolling down the page, the sidebar appears around half-way down and as such you can only see two of the images.
Once a user scrolls past X point (say 400px), I would like the sidebar to start moving with the page. However, it also needs to go back to its original position when the user reaches the top of the page once more.
Is there a fix that can be applied to this code, or a better way of approaching this?
---------------------------------------------------------------------------------
EDIT: position:fixed Problem
When I try to apply position:fixed as per Josh and David's suggestions (either bit of JS code), this happens:
Here is Firebug's read-out of the CSS styles attached to this element:
You can use a plugin for this, but it’s such a simple task that you might as well do it on your own.
Consider this simple markup:
<div id="content">Content</div>
<div id="sidebar"><div>Sidebar</div></div>
And this would be all the javascript you need:
var el = $('#sidebar'),
pos = el.position().top;
$(window).scroll(function() {
el.toggleClass('fixed', $(this).scrollTop() >= pos);
});
Now, it will add a class to the #sidebar div as soon as the user scroll further than the sidebar is positioned, so all you need now is som CSS. I’m applying the fixed positioning to a child element to avoid layout problems:
#sidebar.fixed > div{position:fixed;}
I put up a really simple demo here: http://jsfiddle.net/QZyH3/
You should try the jQuery code found in this tutorial, which replicates Apple's shopping cart sidebar. It has a working demo and a very small code footprint.
why not use css position: fixed; property? of course if you don't mind the div being not smooth but straightly following your scrollTop. I've found it not working only in IE6-- by today, so using fixed position is a good solution I think, otherwise you just get with window.scrollTop of DOM and assign it to your element's absolute position top