this is so simple and I searched but couldn\'t find the exact answer.
All I want to do is have a div that will change color when you click a link. I want to have about 3
Demo: http://jsfiddle.net/jnAem/
JS:
var els = document.getElementsByClassName('change-color'),
target = document.getElementById('target'),
changeColor = function(){
target.style.backgroundColor = this.getAttribute('data-color');
};
for(var i=els.length-1; i>=0; --i){
els[i].onclick = changeColor;
}
HTML:
Note that if you want all color changers to be children of same element, you can use event delegation and reduce the previous code to
JS:
document.getElementById('color-changers').onclick = function(e) {
var color = (e ? e.target : window.event.srcElement).getAttribute('data-color');
if(color){
target.style.backgroundColor = color;
}
}
HTML:
Demo: http://jsfiddle.net/jnAem/1/