- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Function that changes BGcolor onClick
i have written code as ‘ <script>
function changing()
{
var colr= [“blue”,”lightblue”,”green”,”gray”,”lime”,”olive”,”lightgreen”];
for(var i=0; i<colr.length ;i++)
{
document.getElementById(“coloring”).style.backgroundColor=colr[i];
}
}
</script>
<body onclick=”changing()”>;
where coloring is a div element ,
my Idea is to change
<div=coloring> ‘s background color when i click the body of the webpage. i want it to change different colors sequentially as i click.
please help me!.
I think JQ qould be something like this-
var colors = ['red', 'blue', 'green', 'cyan'],
i = 0;
$("body").click(function(){
$("#colouring").css("backgroundColor", colors[i++]);
if (i >= colors.length)
i = 0;
});
Or the same as Paulie_D’s example but in plain ol’ vanilla JavaScript
var colors = ['red', 'blue', 'green', 'cyan'],
i = 0;
var elementToChange = document.getElementById('colouring');
document.body.addEventListener('click', function(event){
elementToChange.style.backgroundColor = colors[++i];
if (i >= colors.length){
i = 0;
}
});
Just for fun you can shorten this further by using the modulus (%) to continuously loop back through the array.
var colors = ['red', 'blue', 'green', 'cyan'],
i = 0;
var elementToChange = document.getElementById('colouring');
document.body.addEventListener('click', function(event){
elementToChange.style.backgroundColor = colors[++i % colors.length];
});