I have a working script which adds the class of "stick" when the div reaches the top of the page so that it remains visible at the top of the page.
$(document).ready(function() {
var s = $("#side-div");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop() ;
if (windowpos >= 670) {
s.addClass("stick");
}
else if ($("body").height() <= ($(window).height() + windowpos)) {
s.removeClass("stick");
}
else {
s.removeClass("stick");
}
});
});
That part works. However, I am trying to "unstick" this div once it reaches the bottom of the page. Actually, I am trying to un-stick it when the footer becomes visible. But I have not even been able to get to that part.
I do realize that there are plugins out there that I can use.
http://viget.com/inspire/jquery-stick-em
However, I am trying to achieve this effect w/o using any plugin. I am actually trying to learn how to script jQuery more than anything else.
If I were interested in solving my problem, using the plugin would be simple & easy. But I am trying to learn why my else if part does not work.
Thank you for any insight.
You are doing okay, there's just a problem with your if else statements and conditions. If you put this on top if (windowpos >= 670) {
, even if you reached the bottom this condition remains true and will still be executed.
I also see you included a var pos = s.position();
but never really used it, so I think what you may be trying to do is to set sticky if you reached the $("#side-div")
's position.
$(document).ready(function() {
var s = $("#side-div");
var pos = s.offset().top;
$(window).scroll(function() {
var windowpos = $(window).scrollTop() ;
if(windowpos + $(window).height() == $(document).height()){
s.removeClass('stick');
}else if(windowpos >= pos){
s.addClass('stick');
}else{
s.removeClass('stick');
}
});
});
Here is a sample fiddle