I have Div element and Im setting its onClick event to null, like this.
child.onclick = null;
In this case child is a DOM element represent that DIV element.
Now the onclick
event is no longer there, and now I want to have it again like this.
child.onclick = new Function();
But that way does not work. I just want to have onclick
behavior as it was before it is set to null.
Can anyone help?
I have Div element and Im setting its onClick event to null, like this.
child.onclick = null;
In this case child is a DOM element represent that DIV element.
Now the onclick
event is no longer there, and now I want to have it again like this.
child.onclick = new Function();
But that way does not work. I just want to have onclick
behavior as it was before it is set to null.
Can anyone help?
Share Improve this question edited Jul 22, 2022 at 22:01 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 19, 2013 at 11:11 Dilan AlexDilan Alex 211 gold badge1 silver badge6 bronze badges 3-
1
Try
document.getElementById('myDiv').onclick= function(){//your code goes here};
– Harsha Venkataramu Commented Jun 19, 2013 at 11:13 -
If you are talking abour removing and attaching onclick functionality on the fly. Surely if you have a named function
function myFunc(){ //code here }
once you've setchild.onclick = null
you can re-attach the functionality you want withchild.onclick = myFunc;
?? – Mark Walters Commented Jun 19, 2013 at 11:15 - Once onClick is set to null we can still click on the DIV but nothing is happened. I just want to have the default behavior of onClick event. I do not have any function defined by me. – Dilan Alex Commented Jun 19, 2013 at 12:38
3 Answers
Reset to default 2// save reference to the old callback function
var oldOnclickFn = child.onclick;
// set onclick to null
child.onclick = null;
// set the onclick to the function that was there before.
child.onclick = oldOnclickFn;
However, you should probably look into addEventListener.
I would suggest using addEventListener
and removeEventListener
:
function handler(e){
}
to add listener:
child.addEventListener('click', handler);
to remove:
child.removeEventListener('click', handler);
NOTE as Mark Walters said, use attachEvent
and detachEvent
for IE < 9
Like this:
document.getElementById('clickme').onclick = function(){ alert('clicked'); };
http://jsfiddle/pJa9W/