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