简体   繁体   中英

Using jquery to check if element has class constantly

I'm using stickyJS to create a sticky header with my wordpress website. I have enqueued the scripts properly and the sticky is working perfectly.

What I am trying to achieve is to constantly check if the nav element that I have set up for the sticky has a class called "is-sticky" and if so change some of the CSS.

Here is the code that I have already:

function stickyInit($)
{
$("#site-navigation").sticky({topSpacing:0});

window.setInterval(check_sticky,500);

function check_sticky(){
    if($("#site-navigation-sticky-wrapper").hasClass("is-sticky")){
        console.log ("Do Something");
    }
}
}

jQuery(document).ready(function ($) {
stickyInit($);
});

This is all the code in the file that I have enqueued to set the nav as sticky.

As you can see I have used setInterval to try and create a loop to constantly test the "#site-navigation-sticky-wrapper" element to see if it has the class mentioned above.

This code works and I get the message in firebug console, but I only ever get it once instead of repeatedly.

So my question is, how do I constantly test this element to see if it has the class "is-sticky" so I can alternate the nav css when it does?

Also when the class "is-sticky" isnt set on the element (after I have scrolled back to the top) how do I set the nav back to its original position? Or will it just do that anyway?

Check this fiddle - it fires repeatedly when the 'is-sticky' class is active & the nav position is automatically restored to its former state when you scroll to the stop.

// Your code
function stickyInit($){

    $("#site-navigation").sticky({topSpacing:0});

        function check_sticky(){
            if ( $("#site-navigation-sticky-wrapper").hasClass("is-sticky") ) {
                console.log ("Do Something");
            }
        }

    window.setInterval(check_sticky,500);
}

jQuery(document).ready(function ($) {

    stickyInit($);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM