Skip to content Skip to sidebar Skip to footer

How To Bind Event To Element?

How to bind event to element in pure javascript: This is what JQuery does, how do you accomplish it with pure javascript? $('#arrow_left') .bind('click', {'c_index': c_index - ite

Solution 1:

You would use element.AddEventListener

target.addEventListener(type, listener[, useCapture]);

And in IE's case (prior to IE9) you would use attachEvent.

bSuccess = object.attachEvent(the_event, function_handler)
//the_event always starts with "on"

Like this:

<inputid="btn"type="button" value="click me" />​​​​​​​​​​​

JS:

functionclick_handler()
{
    alert("clicked");
}
var el = document.getElementById("btn");   
if(el.addEventListener)//check if this exists
{
    el.addEventListener("click", click_handler);   
} else {
    //then we're on IE older than 9
    el.attachEvent("onclick",click_handler);
}​

See the demo: http://jsfiddle.net/E8nYr/2/

Solution 2:

elem.addEventListener(eventType,    
                      handler,      
                      useCapture);  

for IE6,7,8 :

elem.attachEvent (event,            
                  handler);         

That's the old fashioned way, but you are using jQuery anyways so why changing ?

Solution 3:

For non-IE You give it three arguments: the event type, the function to be executed and a boolean (true or false) indicating whether the event handler should be executed in the capturing or in the bubbling phase. If you’re not certain whether you want capturing or bubbling, use false.


element.addEventListener('click',doSomething,false)

//In IE
element.attachEvent('onclick',doSomething)

Post a Comment for "How To Bind Event To Element?"