Hi all,
Fairly new to jQuery and JavaScript in general. I mocked up an example of my problem at http://jsbin.com/alibi3/2/ - with an explanation below.
I have a div that, after a user scrolls past a certain point on the page, is assigned a class of "fixed" so it follows the user down the page. This works fine on its own.
Problem is, the content above that div can be toggled to show/hide - and when it is shown, the fixed class is still being applied at the point it would have been if it was hidden, so it appears to 'jump'.
How do I tell my fixed-class-adding function that the div above has been shown/hidden, and so adjust the point at which the 'fixed' class is added?
Thanks.
HTML:
<div id="drawer">
<a href="#">Click here to toggle drawer</a>
<p id="drawercontents">Here is the stuff in the drawer; hidden by default.</p>
</div>
<div id="article">
blah, blah...
</div>
<div id="nav">
This should follow down the page once we scroll past the start of the article,
and 'stick' back in place when we are back at the top.
</div>
CSS:
#article {
width: 400px;
float: left;
margin-right: 20px;
padding: 20px;
background: #eee;
}
#nav {
width: 200px;
float: left;
background: #ff0;
padding: 20px;
}
#drawer {
width: 660px;
padding: 20px;
color:#fff;
background: #000;
margin-bottom: 10px;
}
.fixed { position: fixed; left: 460px; top: 0px; }
JavaScript:
$(document).ready(function() {
$('#drawercontents').hide();
$('#drawer a').click(function(e){
e.preventDefault();
$('#drawercontents').toggle('fast');
});
var top =$('#nav').offset().top - parseFloat($('#nav').css('marginTop').replace(/auto/, 0));
$(window).scroll(function () {
// what is the y position of the scroll?
var y = $(window).scrollTop();
// whether that's below the start of article?
if (y >= top) {
// if so, add the fixed class
$('#nav').addClass('fixed');
} else {
// otherwise, remove it
$('#nav').removeClass('fixed');
}
});
});