scrollTop does not work

Asked

Viewed 854 times

2

I have a div topoMaior and I want that when the person gives scroll of some 50px, it stays with top:0.

I did it with Jquery:

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

And it didn’t roll.

  • This div has absolute or fixed position?

  • The div has position fixed

  • Have an Event Handler for this? how is this function?

  • 1

    Test this and say what the console shows: http://jsfiddle.net/kj53q3kb/

  • 1

    @Sergio worked! : D and how I would make an immature of it?

  • 1

    @Felipestoker what do you want to cheer up? where’s the ".topoMaior" on the page before applying top: 0 ? if you put HTML I can give an answer with an example

Show 1 more comment

1 answer

2


I think that this idea is missing Event Handler that is activated when a scroll happens.

You can do it like this:

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

To join an animation you can do so:

$(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: http://jsfiddle.net/w84mb94q/


If you want you can do this with CSS, which is the right 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>
<div class="topoMaior"></div>
<div class="main"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.