Reputation: 1240
I have the following script which attempts to change the color of a div, when clicked, with an id of wrapper. I have tried variations of what's below, but can't see the issue. The on click event does not trigger the function.
I have tried changing background-color
to backgroundColor
, which didn't make a difference. I know I'm using a global variable here, please ignore that part:
var wrapper;
function wrapperColorToCoral () {
wrapper.setAttribute('style', 'background-color:LightCoral;');
}
function wrapperColorToGreen () {
wrapper.setAttribute('style', 'background-color:LightGreen;');
}
function colorChange () {
//if (wrapper.getAttribute('style', 'background-color:LightCoral;') === true) {
if (wrapper.style != 'background-color:LightGreen;') {
wrapperColorToGreen();
}
else {
wrapperColorToCoral();
}
}
// INIT FUNCTION
function init () {
wrapper = document.getElementById('wrapper');
wrapper.onClick = colorChange();
}
window.onload = init;
Edit (Working - Thanks Quentin):
var wrapper
function wrapperColorToCoral () {
wrapper.style.backgroundColor="LightCoral";
}
function wrapperColorToGreen () {
wrapper.style.backgroundColor="LightGreen";
}
function colorChange () {
if (wrapper.style.backgroundColor==="LightCoral") {
wrapperColorToGreen();
}
else {
wrapperColorToCoral();
}
}
function init () {
wrapper = document.getElementById('wrapper');
wrapper.addEventListener("click", colorChange, false);
}
window.onload = init;
Upvotes: 0
Views: 1836
Reputation: 944441
onclick
(but you should probably be using addEventListener anyway).()
on the end of a function name will call the function. You want to assign it to a property. Remove the parenthesis. Upvotes: 6