javascript - addEventListener to an element, with the element itself as parameter -


first of all, sorry if title isn't best one, couldn't find better one.

how can set function clickevent div using javascript, , @ same time set parameter of function, div itself?
example:

i have html file has:

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

and js file have following code:

var el = document.getelementbyid("parent").getelementsbyclassname("child")[0]; el.onclick = somefuntion(this); 

but thing is, want this paramenter refer div.child, when click div should pass parameter, dom element, making me able use inside of somefuntion(element) other dom element: element#id, 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 use "e.target" here on, instead of "e"         //e.id (error: undefined); e.target.id (correct)     } } 

solution

just el.addeventlistener("click", somefunction); <- not somefunction()

and use event.target

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

alternative solution

if @jaromandax's solution, simplify to

el.addeventlistener("click",somefunction.bind(null,el)); 

note bind returns function. example should clarify it:

function somefunction(el) {   // if used bind below, results are:   console.log(this); // "this it!"   console.log(el); // clicked element }  a.addeventlistener("click",somefunction.bind("this it!",a)); 

advice

  • somefunction function itself
  • somefunction() function returns

if want coder, shouldn't satisfied it works!. worthy spend time find out why works. without step can't sure if code doesn't contain hidden bugs in cases.

what have in solutions tried programming permutation antipattern - highly recommend reading great wiki article antipatterns.


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -