There are several ways to attach a click handler without using a library. The first is assigning a function to the on[eventname]
property of an element:
element.onclick = function (eventObj) {
alert("textContent" in this ? this.textContent : this.innerText)
}
You can also assign a string of code to be evaluated but it's not as pretty and generally avoided. Another way is to use the w3c standard addEventListener
:
element.addEventListener("click", function (eventObj) {
alert("textContent" in this ? this.textContent : this.innerText)
}, false);
This is not supported by current versions of IE which require attachEvent
instead:
element.attachEvent("onclick", function () {
alert(event.srcElement.innerText);
});
IE has problems applying the function to the element that fired the event, so this
will not correctly point to that element with attachEvent
.
The first method element.onclick
is useful for x-browser compatibility and quick coding, but you can only assign a single function to the property. Using attachEvent
and addEventListener
you can attach as many functions as you like and they will all fire correctly. You can create a cross browser semi-equivalent doing simple functionality checks in your code:
if ("addEventListener" in element)
element.addEventListener("click", function (eventObj) {
alert("textContent" in this ? this.textContent : this.innerText)
}, false);
else
element.attachEvent("onclick", function () {
alert(event.srcElement.innerText);
});