Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener to an element, with the element itself as parameter

First of all, sorry if the title isn't the best one, I couldn't find a better one.

How can I set a function as clickEvent for a Div using javascript, and at the same time also set the parameter of the function, to be the Div itself?
For example:

I have a HTML file that has:

<span id='parent'>
    <div class='child'></div>
</span>

And a JS file where I have the following code:

var el = document.getElementById("parent").getElementsByClassName("child")[0];
el.onclick = someFuntion(this);

But the thing is, I want that the this paramenter refer to the div.child, so that when I click the Div it should pass itself as a parameter, as a DOM element, making me able to use it inside of someFuntion(element) just like any other DOM element: element#id, for example.

Solutions tried:

el.addEventListener("click", someFuntion(event), false);
el.addEventListener("click", someFuntion(this), false);
el.addEventListener("click", someFuntion(el), false);
$("#parent #child").bind("click", someFuntion(this));
el.onclick = someFuntion(divIntoSpan);

SOLUTION:
el.onclick = someFuntion;

function someFunction(e){
    if(e.target){
        //remember to use "e.target" from here on, instead of only "e"
        //e.id (error: undefined); e.target.id (correct)
    }
}
like image 277
alexluz Avatar asked Dec 05 '22 03:12

alexluz


2 Answers

Solution

Just do el.addEventListener("click", someFunction); <- not someFunction()

and then use event.target

function someFunction(e) {
   if(e.target) ...
}

Alternative solution

If you like @JaromandaX's solution, you could simplify it to

el.addEventListener("click",someFunction.bind(null,el));

Note that bind returns function. This example should clarify it:

function someFunction(el) {
  // if used with bind below, the results are:
  console.log(this); // "This is it!"
  console.log(el); // the clicked element
}

a.addEventListener("click",someFunction.bind("This is it!",a));

Advice

  • someFunction is the function itself
  • someFunction() is what the function returns

If you want to be a good coder, you shouldn't be satisfied with It works!. It is worthy to spend some time to find out why it works. Without this step you can't be sure if your code doesn't contain hidden bugs in some cases.

What you have in Solutions tried is Programming by permutation which is an antipattern - I highly recommend reading this great wiki article about antipatterns.

like image 89
Jan Turoň Avatar answered Dec 09 '22 13:12

Jan Turoň


if, for some reason you must do it the way you want

el.addEventListener('click', function(e) { 
    someFunction(e.target);
}, false);

but the answer given by Jan Turoň is the preferred way

like image 26
Jaromanda X Avatar answered Dec 09 '22 15:12

Jaromanda X