• Hi,

    I was wondering how to add a class to an element when the user scrolls to a certain point. On the current project I need to have a smaller header drop into view when the larger one scrolls out of sight. Even if there may be a more specified way of doing this, I would like the “add class” option because it would be more versatile.

    I am a relative newbie with jquery so I would prefer javascript. However, any help would be much appreciated.

    Thank you.

Viewing 5 replies - 1 through 5 (of 5 total)
  • 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.

    Thread Starter aschoenbrun

    (@aschoenbrun)

    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. ??

    Thread Starter aschoenbrun

    (@aschoenbrun)

    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");
    	    }
    	});
    });

    ??

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Add class when scroll a certain amount’ is closed to new replies.