Hi,
You can use the following jQuery to do such task:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$(".clearHeader").addClass("darkHeader");
} else {
$(".clearHeader").removeClass("darkHeader");
}
});
It will add the class darkHeader to the element with class .clearHeader.
Thanks Hardeep.
It seems, though, that I get an error when applied. Console outputs: “$ is not a function”. Only when I replace all instances of “$” with “jQuery” does it work.
I enqueued the script in functions.php as follows:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'HeaderChangeOnScroll', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/assets/js/HeaderChangeOnScroll.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
Have I done something wrong?
Thanks
Not really. If it works with jQuery then that’s fine too. 🙂
True!
But it would be nice to write things shorthand if possible.
But this will do:
jQuery( document ).ready(function( $ ) {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$(".clearHeader").addClass("darkHeader");
} else {
$(".clearHeader").removeClass("darkHeader");
}
});
});
🙂