0

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;
1
  • 1
    Change your init to: wrapper.onclick = colorChange; Commented Jul 25, 2013 at 14:02

1 Answer 1

6
  1. JavaScript is case-sensitive. The property is onclick (but you should probably be using addEventListener anyway).
  2. Putting () on the end of a function name will call the function. You want to assign it to a property. Remove the parenthesis.
Sign up to request clarification or add additional context in comments.

6 Comments

thanks so much! - so you recommend I do something more like: wrapper.addEventListener("click", colorChange, false);?
@Quentin - could you tell me why it only listens once, but if I click a second time, it doesn't run the function again?
It does run the function again. wrapper.style doesn't give you the value you think it does.
@Quentin - still not getting it to work, I've made some edits above - when I do, wrapper.style.backgroundColor="LightCoral"; in the console it works, but the function still doesn't seem to run again...
= is an assignment, not a comparison, it will always be true.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.