简体   繁体   中英

Changing Element Classes with jQuery using conditionals and a timer

Essentially i have three different classes that can be applied to an element on my page. Each holds a different background image and i want to use JQuery to find out which class is currently there and the remove that class and replace it with another. and then set a timer on it to run the function every 5000ms this is what my code looks like

$(document).ready(
    function(){
    var toggleImage = function(){
        if($(".home").hasClass("home1")){
            $(".home").removeClass("home1").addClass("home2")       }
        elseif($(".home").hasClass("home2")){
            $(".home").removeClass("home2").addClass("home3")
        }
        elseif($(".home").hasClass("home3")){
            $(".home").removeClass("home3").addClass("home1")
        }

    }

    setInterval(toggleImage(), 5000);​

    });

The class of home will always be there and im just trying to add and remove the other classes on the element. Im coming from PHP so im thinking maybe my syntax could be off.

You have to pass a function to setInterval . Currently you are calling toggleImage and pass its return value, which is undefined .

Don't call the function:

setInterval(toggleImage, 5000);​

At least in Firefox you would have gotten a runtime error:

Error: useless setInterval call (missing quotes around argument?)


Im coming from PHP so im thinking maybe my syntax could be off.

You are right, elseif should be else if . This is a syntax error and you should have seen it in the console as well.


Learn how to debug JavaScript to find syntax and runtime errors on your own.

You want to pass setInterval a function. Calling toggleImage() runs the function and ends up passing setInterval the result. The correct syntax should be:

setInterval(toggleImage, 5000);

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