Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript addEventListener without selecting children

I need to use javascript only for this project. Sorry, no jQuery (I feel ashamed as well).

I am adding an addEventListener to a div. "Problem" is that it applies to all its children, too.

Is there a way to avoid this, and have the listener work only for that div?

Thankd in advance.


my code looks like this:

document.getElementById(myObj.id).addEventListener("mousedown", myObjDown, false);

function myObjDown() {
  //do stuff here
}
like image 581
john smith Avatar asked Dec 17 '12 16:12

john smith


People also ask

Is addEventListener deprecated?

addListener() Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

What is the benefit of using addEventListener instead of inline event handlers?

addEventListener() has multiple advantages: Allows you to register unlimited events handlers and remove them with element. removeEventListener() . Has useCapture parameter, which indicates whether you'd like to handle event in its capturing or bubbling phase.

Which Javascript function is used to select the child tag from the parent element?

jQuery children() function. jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.


1 Answers

You can tell which element the event actually fired on by reading event.target in your callback.

var el = ...
el.addEventListener('click', function(event){
  if (el !== event.target) return;

  // Do your stuff.

}, false);

The other option would be to have handlers bound to the child elements to prevent the event from reaching the parent handler, but that is more work and potentially hides events from things that might actually be listening for them above the parent.

Update

Given your example code, you should be able to do this.

var el = document.getElementById(myObj.id);
el.addEventListener("mousedown", myObjDown, false);

function myObjDown(event) {
  if (el !== event.target) return;

  //do stuff here
}

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

like image 150
loganfsmyth Avatar answered Oct 11 '22 19:10

loganfsmyth