Saif Abushama
Saif Abushama

Reputation: 73

How can I change the background color randomly with the Javascript?

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

Upvotes: 2

Views: 5118

Answers (4)

mickeybroud
mickeybroud

Reputation: 1

JavaScript:

<div id="backgroundsection">
    <button id="buttonClick">Change color</button>
    <h4>HEX Color:<span class="texthex"></span></h4>
</div>

<style>
    #backgroundsection {
        display: flex;
        justify-content: center;
        align-items: center;
        color: #ffffff;
        background-color: #000000;
        height: 100px;
    }
</style>

<script>
    const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']; //array of all hex color values
    const textColor = document.querySelector(".texthex") //find an element for the subsequent replacement of the text in it with the current hex color
    const buttonClick = document.getElementById("buttonClick"); //color change button

    buttonClick.addEventListener("click", function () { //click event
       let colorhex = "#"; // a variable that will contain a hex color
        for(let i=0; i<6; i++) { //a loop that creates 6 values
            colorhex += hex[rundomnumber()];
        }
        textColor.textContent = colorhex; //substitute the current hex color value in span class="texthex"
        document.body.style.backgroundColor = colorhex; //change the body color
    });
    
    function rundomnumber() { 
        return Math.floor(Math.random() * hex. length); //a function that creates a random value from an array "hex"
    }


</script>

Upvotes: 0

sonam gupta
sonam gupta

Reputation: 785

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>

Upvotes: 4

Alaa Mohammad
Alaa Mohammad

Reputation: 665

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);
});

Upvotes: 5

Uma Kanth
Uma Kanth

Reputation: 5629

<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>

Upvotes: 5

Related Questions