Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>elWraper.onclick = (function(){ // misc stuff here //event handler return function(e){ e = e || window.event; var t = e.target || e.srcElement; //manipulations with "t" variable } })(); </code></pre> <p>In standards compliant browsers the event object is the first parameter passed into the callback function. In IE it is a global variable (which is what <code>e = e || window.event</code> is trying to determine). Therefore, the function that you return by the <code>immediately executed function</code> should accept the event object declared as its first (and usually only) argument.</p> <hr> <p><strong>Clarification</strong></p> <p>Since people are wondering (and probably they are wondering why the OP accepted this answer) there are uses for this that is not clear from the OP's question. One is to create a closure to a variable to track something:</p> <pre><code>/* Count number of clicks, * WITHOUT USING GLOBAL VARS! */ el.onclick = (function(){ var counter = 0; return function(e){ e = e || window.event; var t = e.target || e.srcElement; counter ++; alert('detected '+counter+' clicks!'); // do stuff with t or e ... } })(); </code></pre> <p>also, this is the classic way of assigning event handlers in loops:</p> <pre><code>/* Use double closure to break closure in loop! */ for (var i=0; i&lt;stuff.length; i++) { var el = stuff[i]; el.onclick = (function(x){ return function(e){ e = e || window.event; var t = e.target || e.srcElement; alert(x); // do stuff with t or e ... } })(i); } </code></pre> <p>Or maybe the OP just thought that he could 'cache' the event object and mistakenly believed he could use this to do it. In which case, reading my explanation (instead of just the code) should enlighten the reader as to why that would be a bad idea.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload