Change Background Color Of Webpage Using Javascript
I am a noob to Javascript so I am struggling with how to do this. I have to change the background color of my webpage when the user clicks on one of these three buttons. This is my
Solution 1:
As long as the IDs of the elements are valid CSS colours, you can just read them from the attribute:
Array.prototype.forEach.call(document.getElementsByTagName('li'), function (el) {
el.addEventListener('click', function (e) {
document.body.style.background = el.id;
})
});
Something like this fiddle.
Solution 2:
Html
<ul id="colors">
<li id="yellow">yello</li>
<li id="orange">orange</li>
<li id="red">red</li>
</ul>
Javascript
var colors = document.getElementById('colors');
colors.addEventListener('click', function(e) {
var el = e.target,
color = el.id;
document.documentElement.style.backgroundColor = color;
});
That works... http://jsfiddle.net/Ayh3q/
Solution 3:
You may try this (Example)
HTML:
<ulid="colorSet"><li>Yellow</li><li>Orange</li><li>Red</li></ul>
JS:
window.onload = function(){
var ul = document.getElementById('colorSet');
ul.onclick = function(e){
var evt = e || window.event;
var target = evt.target || evt.srcElement;
document.body.style.backgroundColor = target.innerHTML;
};
};
Post a Comment for "Change Background Color Of Webpage Using Javascript"