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)
}
}
Just do el.addEventListener("click", someFunction);
<- not someFunction()
and then use event.target
function someFunction(e) {
if(e.target) ...
}
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));
someFunction
is the function itselfsomeFunction()
is what the function returnsIf 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With