Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

set minus instead of plus... you will see the blue color which id in my example under the "else" statement.

working fiddle http://jsfiddle.net/4YaPw/

$(document).ready(function() {
    $(window).scroll(function() {
        var pos = $("#side-div").position();     
        var windowpos = $(window).scrollTop();

        if (windowpos >= 670)
        {
            $("#side-div").css('background-color', '#8a7b70'); //grey
        } 

        else if ($("body").height() <= ($(window).height() - windowpos))
        {
            $("#side-div").css('background-color', '#ff5400'); //orange
        }
        else
        {
            $("#side-div").css('background-color', '#6f8cc0'); //blue
        }
    });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top