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><scripttype="text/javascript">functionfunc()
{
//alert(getRandomColor());document.body.style.backgroundColor = getRandomColor();
}
functiongetRandomColor() {
var letters = "0123456789ABCDEF".split('');
var color = "#";
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script></head><bodyonload="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);
});
functionget_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?"