Search code examples
javascriptjqueryhtmladdclassscrolltop

Jquery addclass after scrolling 500px


I want to add a class to a div after scrolling 500px down the page using jquery. I found a way of doing it but it's an immediate transition, I want to be able to controll how long it takes to add the class like with the normal Jquery addclass.

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();
    if (scroll >= 500) {
        $(".nav").addClass("navnewclass");
    }
});

I tried doing this:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();
    if (scroll >= 500) {
        $(".nav").addClass("navnewclass", 2000);
    }
});

but it was the same.


Solution

  • I want to be able to controll how long it takes to add the class like with the normal Jquery addclass.

    addClass is always instantaneous, it's not part of the animation suite.

    There are plug-ins that will do class-based animations for you (most notably jQuery UI's addClass override), but jQuery itself does not. Simply adding jQuery UI to your page will make your second example work. But there are other options as well.

    Your options are to use one of those plug-ins, or animate the properties directly (using animate) rather than using a class. Note that jQuery only animates certain kinds of properties (not, notably, colors — jQuery UI adds support for animating colors as well).

    Here's an example animating a class (with colors) using jQuery UI: Live Copy | Live Source

    <style>
    .testing {
      color: white;
      background-color: blue;
    }
    </style>
    
    <!-- ...and later in the body... -->
    
    <p>After half a second, the div below will spend two seconds animating the addition of a class.</p>
    <div class="nav">This is a test .nav element</div>
    <script>
    setTimeout(function() {
        $(".nav").addClass("testing", 2000);
    }, 500);
    </script>