Reputation: 21
I would like to know how to disable the onclick event of a certain class. I am aware that you can use the CSS pointer-events: none;
however I would like for the hover events to still work, just onclick to be disabled.
Also how do I re-enable them later? For example:
if (document.getElementById('wuzi').backgroundColor == "green" ) {
//disable onclick
} else {
//enable onclick
}
Thank you
Upvotes: 2
Views: 2516
Reputation: 636
I hope this will helps you
if (document.getElementById('wuzi').style.backgroundColor === "green" ) {
//disable onclick
this.onclick=null
} else {
//enable onclick
this.onclick=my_function;
}
Just define your function as you want
function my_function()
{
alert('enable');
}
Upvotes: 0
Reputation: 2308
You can just add and remove the listener to 'click':
var wuzi = document.getElementById('wuzi');
if (wuzi.backgroundColor === "green" ) {
wuzi.removeEventListener('click');
} else {
wuzi.addEventListener('click', clickHandler);
}
where clickHandler is your function for handling the click.
Upvotes: 3
Reputation: 2010
try returning false onclick:
var element = document.getElementById('wuzi')
if (element .backgroundColor == "green" ) {
//disable onclick by returning false from onclick
element.onclick = return false;
} else {
//enable onclick or do some appropriate action
}
Upvotes: 0
Reputation: 133403
I would suggest you to add CSS class instead of comparing backgroundColor
, then check set disabled
property based on class
var element = document.getElementById('wuzi');
element.disabled = element.classList.contains("foo");
Upvotes: 0
Reputation: 1222
You can try as below:
var element = document.getElementById('wuzi')
if (element .backgroundColor == "green" ) {
//disable onclick
element.onclick = '';
} else {
//enable onclick
}
Upvotes: 1