Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events
    text
    copied!<p>In order to add events we could use this simple <strong>1st solution</strong>:</p> <pre><code>function AddEvent(html_element, event_name, event_function) { if(html_element.attachEvent) //Internet Explorer html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);}); else if(html_element.addEventListener) //Firefox &amp; company html_element.addEventListener(event_name, event_function, false); //don't need the 'call' trick because in FF everything already works in the right way } </code></pre> <p>or this <strong>2nd solution</strong> (that adds inline events):</p> <pre><code>function AddEvent(html_element, event_name, event_function) { var old_event = html_element['on' + event_name]; if(typeof old_event !== 'function') html_element['on' + event_name] = function() { event_function.call(html_element); }; else html_element['on' + event_name] = function() { old_event(); event_function.call(html_element); }; } </code></pre> <p>These are <strong>both cross-browsers</strong> and can be used in this way:</p> <pre><code>AddEvent(document.getElementById('some_div_id'), 'click', function() { alert(this.tagName); //shows 'DIV' }); </code></pre> <p>Since I have the feeling <code>attachEvent/addEventListener</code> are used more around in events handling implementations, I'm wondering: </p> <p><strong>Are there any disadvantages/drawbacks against using the 2nd solution that I might better be aware of?</strong></p> <p>I can see two, but I'm interested in more (if any):</p> <ol> <li>the 2nd solution screws up innerHTML of elements by adding events inline</li> <li>Using 2nd solution I can easily remove all functions associated with a certain event type (<code>html_element['on' + event_name] = null</code>), but I can not use <code>detachEvent/removeEventListener</code> to remove exactly a specific function.</li> </ol> <p>Any answers like: "use jQuery" or any other FW are pointless!</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