Reputation: 65
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.
Upvotes: 2
Views: 20496
Reputation: 4433
you can do that using jQuery or $ sign
example:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$("#logo-not-scroll").addClass("blue1");
}
else{
$("#logo-not-scroll").removeClass("blue1");
}
});
or
jQuery(window).scroll(function() {
var scroll = jQuery(window).scrollTop();
if (scroll >= 100) {
jQuery("#logo-not-scroll").addClass("blue1");
}
else{
jQuery("#logo-not-scroll").removeClass("blue1");
}
});
Upvotes: 0
Reputation: 530
IT WILL WORK FINE FOR ME.
$(document).scroll(function() {
var scroll = $(this).scrollTop();
if (scroll >= 500) {
setTimeout('$(".nav").addClass("navnewclass")',1000);
}
});
instead of 1000 U can just set your time.
Upvotes: 0
Reputation: 1074268
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>
Upvotes: 2