简体   繁体   中英

onClick event is not triggering function

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;

Thank you for your help

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM