Event detection in Javascript
I can't find good documentation on this awesome, so I'm posting it here.
What's the raw javascript equivalent to this:
$(elem).click(function(){
alert(this.text());
});
All I can find is this <elem onlick="func()" />
which is not what I want, I want to be able to do this with only javascript not in the context of an element.
a source to share
Assuming which elem
is a node element (if not, you will need to use your in-use selector getElementById
or whatever):
elem.onclick= function() {
var text= 'textContent' in elem? elem.textContent : elem.innerText;
alert(text);
};
textContent
is the standard way to get text from an element; innerText
is the way of IE. (There are a few differences, but hopefully nothing that will affect you.) If you need to support older / obscure browsers that don't have either, you will have to do a tedious tree walk to get all the text (that's what jQuery text()
does.)
(I'm guessing what you want from this.text()
. It doesn't actually work - presumably you meant $(this).text()
.)
a source to share
There are several ways to connect a click handler without using a library. The first assigns a function to an on[eventname]
element property :
element.onclick = function (eventObj) {
alert("textContent" in this ? this.textContent : this.innerText)
}
You can also assign a line of code to be evaluated, but that's not 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 instead attachEvent
:
element.attachEvent("onclick", function () {
alert(event.srcElement.innerText);
});
IE has problems applying the function to the element that triggered the event, so this
it won't correctly point to that element with attachEvent
.
The first method element.onclick
is useful for x-browser compatibility and fast coding, but you can only assign one function to a property. Using attachEvent
and addEventListener
, you can attach as many functions as you like and they will all work correctly. You can create a cross-browser semi-equivalent by doing simple function 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);
});
a source to share