Brent
Brent

Reputation: 2485

jQuery .scrollTop confusion

Could anyone help me with this JavaScript?

I want a div to show when you scroll down over 1000 pixels, currently it works with the script below but it shows instantly when scrolled.

I tried setting it to >1000 and it doesn't show at all?

Any ideas?

$(window).scroll( function(){

    /* Check the location of each desired element */
    $('.hideme').each( function(i){

        /* If the object is completely visible in the window, fade it in */
        if ($(this).scrollTop() < 1000){
            $(this).animate({'opacity':'1'},900);
        }
    }); 
});

Upvotes: 1

Views: 366

Answers (2)

Barrie Reader
Barrie Reader

Reputation: 10713

Hopefully this will help?

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script>
    $(window).scroll( function(){
        /* Check the location of each desired element */
        $('.hideme').each( function(i){
            console.log($(window).scrollTop());
            if ($(window).scrollTop() < 500){
                $(this).stop().animate({
                    opacity: 1.0
                },900);
            } else {
                $(this).stop().animate({
                    opacity: 0.0
                },900);
            }
        }); 
    });
    </script>
</head>
<body style="height: 1500px;">

<div style="width: 400px; height: 50px; position: absolute; top: 500px; background-color: silver; opacity: 0.0;" class="hideme">asdsa</div>

</body>
</html>

I've changed the functionality slightly, hopefully you'll know what to do ;)

Upvotes: 1

Brent
Brent

Reputation: 2485

Oh Dear.. Fixed :)

if ($(window).scrollTop() > 1200 ) {

Needed to set from the window not the .hideme div ($this)

Upvotes: 0

Related Questions