Javascript addEventListener without selecting children

I need to use javascript only for this project. Sorry, no jQuery (I am ashamed too).

I add addEventListener to the div. The β€œproblem” is that it applies to all her children.

Is there a way to avoid this, and the listener only works for this div?

Thanks in advance.


my code is as follows:

 document.getElementById(myObj.id).addEventListener("mousedown", myObjDown, false); function myObjDown() { //do stuff here } 
+10
javascript events
source share
3 answers

You can indicate on which element the event that the reading was made on, event.target in your callback.

 var el = ... el.addEventListener('click', function(event){ if (el !== event.target) return; // Do your stuff. }, false); 

Another option is for the handlers to bind to children to prevent the event from being received from the parent handler, but this works more and potentially hides events from things that can actually listen to them above the parent.

Update

Given your sample code, you can do it.

 var el = document.getElementById(myObj.id); el.addEventListener("mousedown", myObjDown, false); function myObjDown(event) { if (el !== event.target) return; //do stuff here } 

As well as a general note, keep in mind that none if this will work on IE <9, because addEventListener is not supported on them.

+18
source share

You can use the currentTarget event property

 el.addEventListener('click', function(event) { if (event.currentTarget !== event.target) { return; } // Do your stuff. }, false); 

More information: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

+5
source share

Here's an alternative that saves your myObjDown function according to a typical event handler. (using e.target as a reference to the event invocation element)

 var CssSelector = "div.className"; var elms = document.querySelectorAll(CssSelector); for (i = 0; i < elms.length; i++) { elms[i].addEventListener("mousedown", myObjDown.bind(null, {"target":elms[i]}, false); } function myObjDown(e) { console.log("event: %o - target: %o", e, e.target); var elm = e.target; //do stuff here } 

It has been suggested that ..

this method may cause memory leak with versions of some browsers. If anyone is experiencing this or has valuable information. Please comment.


an alternative in this regard would be

 var CssSelector = "div.className"; var elms = document.querySelectorAll(CssSelector); for (i = 0; i < elms.length; i++) { elms[i].addEventListener("mousedown", myObjDown.bind(null, elms[i].id}, false); } function myObjDown(id) { console.log("element: %o ", document.getElementById(id)); //do stuff here } 
+1
source share

All Articles