Stop Javascript event from affecting child elements - Stack Overflow

I have a script that creates an element, and part of the creation process is to add an onclick event (u

I have a script that creates an element, and part of the creation process is to add an onclick event (using addEventListener), but when I click a child element, the onclick event of the parent is triggered. How can I prevent the click from being detected when the source is a child element?

I have a script that creates an element, and part of the creation process is to add an onclick event (using addEventListener), but when I click a child element, the onclick event of the parent is triggered. How can I prevent the click from being detected when the source is a child element?

Share Improve this question asked Aug 20, 2012 at 18:47 tophergtopherg 4,3234 gold badges38 silver badges73 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Use event.stopPropagation(). This stops the bubbling of Javascript events and will only allow the events applied to the targetted element to execute;

window.addEventListener("click", function(event){

    // event here

    event.stopPropagation();
}, false);

The problem is that the event is bubbling up to the parent.

In the child's onclick event, tell the event to stop propagation:

onclick = function (event) {
    // ...
    event.stopPropagation();
};

the parent click handler: (check on the id of the clicked element)

function handler(e){
  if(e.target.id != "parentID") return;
  ....
}

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

相关推荐

  • Stop Javascript event from affecting child elements - Stack Overflow

    I have a script that creates an element, and part of the creation process is to add an onclick event (u

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信