Javascript: Getting IE To Return this
Posted on Thursday, September 20th, 2007
Internet Explorer can make the simplest piece of code hard. It turns a simple function into a headache. The standards say one thing, but Internet Explorer doesn’t just disobey those standards, it comes up with a different function and a different idea of what that standard even meant. All I want is that when you click on an element to trigger a function, you can refer to the element using this. Let me explain.
Simple Javascript Functions… Really?
I am gaining a lot of experience and practice with javascript in my new job and I am really enjoying it. I’ve dealt with some complex stuff and some seemingly simple stuff. But sometimes it is the simplest of functions that cause the biggest problems.
All I needed to do was create a page with a few <textarea>s that held text for someone to copy. To aid in this, I was to write a short javascript function that would automatically select the text when the <textarea> was clicked on. Here is the function that will do it:
function selectText() {
this.focus();
this.select();
}
Attach selectText() to the onClick event for each <textarea> and I was sorted.
Except For One Thing…
Internet Explorer, in all its wisdom, returns the window object as the result of this regardless of the element that triggered the event. Firefox and all other sane browsers return the element as you would expect. Quirksmode explains this much better than I can.
I spent forever searching for a way to return the element that triggered the event so that I could use the function, finally stumbling across a mention of event.srcElement in a forum. Looking it up, I discovered that this was the function I needed. However, using it took a more roundabout method than hoped.
When attaching an event to an element, you can only give the reference to the function, passing parameters is not allowed. To pass event.srcElement to the event that I was attaching I needed an anonymous function. Let me illustrate with code:
For standards compliant browsers:
textareas[i].addEventListener(’click’, selectText, false);
For Internet Explorer:
textareas[i].attachEvent(’onclick’,function () {
IEselectText(event.srcElement);
});
Got There In The End
Here is the code I finally produced, with a little example of how it works.
So, if you want to use this don’t forget event.srcElement.
(Unless there’s a much better way, but I spent a good while searching for this and I didn’t get anything better!)
If you enjoyed this post, why not subscribe to Unintentionally Blank
Comments
Leave a Comment