scrollTop does not work

2

I have a% div of% and I want it when the person scrolls about 50px, it has topoMaior .

I did this with Jquery:

if ($(window).scrollTop() > 50){
    $(".topoMaior").css("top","0");
}

And it did not roll.

    
asked by anonymous 18.12.2014 / 18:11

1 answer

2

I think the event handler that is activated when a scroll happens is missing on this idea.

You can do this like this:

$(window).scroll(function () {
    // correr código
});

To merge an animation you can do this:

$(window).scroll(function () {
    if ($(window).scrollTop() > 50) {
        $(".topoMaior").stop().animate({top: 0});
        $(".topoMaior").css("background", "#ccf");
    } else {
        $(".topoMaior").stop().animate({top: 200});
        $(".topoMaior").css("background", "#669");
    };
});

jsFiddle: link

If you want you can do this with CSS, which is the most correct way, using JS only to apply a class. Example:

$(window).scroll(function () {
    if ($(window).scrollTop() > 50) $(".topoMaior").addClass('scroll');
    else $(".topoMaior").removeClass('scroll');
});
.topoMaior {
    padding: 20px;
    background: #669;
    position: fixed;
    top: 100px;
    width: 100%;
    transition: all 1s;
}
.main {
    height: 2000px;
}
.scroll {
    top: 0px;
    background-color: #ccf;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="topoMaior"></div>
<div class="main"></div>
    
19.12.2014 / 15:58