dom - After OnClick is set to null how do I have Onclick behavior again in JavaScript - Stack Overflow

I have Div element and Im setting its onClick event to null, like this.child.onclick = null;In this ca

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 set child.onclick = null you can re-attach the functionality you want with child.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
Add a ment  | 

3 Answers 3

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/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742329837a4423492.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信