Reputation: 24699
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 - item_limit },
function(e)
{
var r = e.data.c_index;
}
Upvotes: 1
Views: 577
Reputation: 19465
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:
<input id="btn" type="button" value="click me" />
JS:
function click_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/
Upvotes: 2
Reputation: 100195
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)
Upvotes: 1
Reputation: 7536
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 ?
Upvotes: 2