Generate random class with Jquery

Asked

Viewed 140 times

0

Opa! Was needing that when the function was executed, the class that the #body would receive, were random among the existing ones. Example:

            $(document).ready(function(){
                $('#random').click(function(){
                    $('#body').addClass('red');
                });
            });

When running #Random choose a value between ('red', 'green', 'blue', 'Yellow') and apply to .addClass. Some Jquery god can help me with that?

1 answer

1


You don’t have to be a jQuery God for that :)

To randomly set the color when the page is loaded just use this:

var colors = ['red', 'green', 'blue', 'yellow']
var random_index = Math.floor(Math.random() * 100) % colors.length
var random_color = colors[random_index]

$(document).ready(function(){
    $('#random').click(function(){
        $('#body').addClass(random_color);
    });
});

To change the class when the user wants you need to put some form with which the user can inform this, like a button.

<button id="changeColor"></button>
<script>
    $('#changeColor').click(function(){
        //Como você já criou o array colors antes, você não precisa criar novamente.
        random_index = Math.floor(Math.random() * 100) % colors.length
        random_color = colors[random_index]
        $(colors).each(function(index, value){
            $('#body').removeClass(value);
        });
        $('#body').addClass(random_color);
    });
</script>
  • It works, but only once. In this case, I wanted the user to change color whenever he wanted. Is it possible? ;D Thanks.

  • 1

    I modified the answer so that it can meet what you want.

  • Perfect! It was the way I wanted it :D Thank you!!!

  • always good to help ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.