Search code examples
javascriptjqueryhtmlcsstoggleclass

toggle a random class with jquery


the idea is having a button that, when clicked, adds a random class picking it from an array to another div. what i want is having that same button to remove any randomly added class from it when i re-click it.

here's a fiddle: https://jsfiddle.net/jLmj7bwk/1/

and this is the function

$(".button").click(function() {

    var classes = ['one', 'two', 'three'];
    var randomnumber = Math.floor(Math.random() * classes.length); 

    $(".element").toggleClass(classes[randomnumber]);   

    if  ($(this).text() == "cancel added class")
        $(this).text("add random class")


    else
        $(this).text("cancel added class");

});

this does add a class, but it keeps on adding them without removing it. could you help? thanks a lot!


Solution

  • How is this?

    https://jsfiddle.net/jLmj7bwk/3/

    $(".button").click(function() {
    
    var classes = ['one', 'two', 'three'];
    var randomnumber = Math.floor(Math.random() * classes.length); 
    
    if($(this).text() === "cancel added class")
    {
        $(".element").removeClass(classes.join(' '));
        $(this).text("add random class");
    }
    else
    {
    $(".element").addClass(classes[randomnumber]);
    $(this).text("cancel added class");
    }
    
    }); 
    

    .removeClass can take multiple classes in a a single call if they are separated by spaces, so if you remove all the classes from the array and then add a random one, it works.

    Note that it may sometimes look like the colour didn't change. It did, but due to the array being small, the chance of the colour being the same is high.