Skip to content Skip to sidebar Skip to footer

How Can I Change The Background Color Randomly With The Javascript?

I want to change the background colour once the user refresh the page

Solution 1:

You can do it by jQuery, Please check the code below :

$(document).ready(function() {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
    $("#background").css("background-color", '#' + randomColor);
});

Solution 2:

<html>
<head>
<script type="text/javascript">
	function func()
	{
		//alert(getRandomColor());
		document.body.style.backgroundColor = getRandomColor();
	}
	
function getRandomColor() {
    var letters = "0123456789ABCDEF".split('');
    var color = "#";
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
</script>
</head>
<body onload="func()">

</body>
</html>

Solution 3:

You have to create a function for that which runs on document ready as:

<script type="text/javascript>
    $(document).ready(function() {
    var random_color = get_random_color();
        $("#background").css("background-color", random_color);
    });
    function get_random_color() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
</script>

Post a Comment for "How Can I Change The Background Color Randomly With The Javascript?"