Generate random class with JQuery

0

Oops! It was pointed out that when the function was executed, the class that #body would receive would be random among existing ones. Example:

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

Running #random chooses a value between ('red', 'green', 'blue', 'yellow') and applies to .addClass . Can some JQuery god help me with this?

    
asked by anonymous 24.06.2016 / 08:04

1 answer

1

You do not have to be a jQuery god for this:)

To put the color randomly when the page loads, 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 way that the user can inform it, 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>
    
24.06.2016 / 08:42