What is 'this?'

Just recently, Real Travel started to run into an issue with Internet Explorer alone when it came to Javascript calls. Unfortunately, this issue had been going on for about a week hidden to us with the exception that we were losing some important revenue from our “Check Rates Boxes” (CPCs) found through out the site. A little diagnosis and it turns out that IE users were not getting click throughs from our forms to go to our partners. Luckily, good ol’ IE threw a nice cryptic Javascript error — sarcasm, but I had seen this issue before and went right to the source.

A common programming method

There is a big movement to making Javascript unobtrusive which I am completely for. This makes pages degrade nicely when end users have Javascript turned off, which is usually a very low occurrence unless you are a uber-geek and want to miss out on the cool features a site may have to offer.

When Real Travel noticed the revenue loss issue, we were still currently converting over from the Prototype library to using jQuery, which is a huge advocate of unobtrusive js. Some of our forms were still using the “onSubmit” method to submit data and come to find out this was part of the problem.

To run some our Classes we created for the CPCs, we were using this on our form tag:

1
onSubmit="new TravelService(this).go()"

Now this worked in every other browser out there besides Internet Explorer. The this keyword was throwing IE completely off giving us the error that “This object can not perform this method…” Now this is a very commonly used programming method to signify that we want the target (the form) to be the actuator or owner of the event. So in our TravelService Class we would run methods on elements contained in the form by way of the target.

Unfortunately, IE is not very intuitive and didn’t understand that we were telling it to use the form object as the target. Apparently the way IE thinks, which is completely not what you would expect, this refers to the window object. In other words, IE thought we were telling it to run the methods on all the elements in the window, not the form. This threw up the red flag for IE as it could not find some of the objects we were requesting because they were in other parts of the DOM.

The solution

Like I mentioned, the current code was not unobtrusive, but in the process to be converted, so we had to make a quick patch to the live site to regain our clicks. The quick way to do this was to pass in the id of the form element to the Class.

1
onSubmit="new TravelService($('form_id')).go()"

This allowed IE to understand that we were wanting the target to be the form not the window.

Kind of a bummer that IE had to be the only one to not understand this very simple idea, but when it’s about 90% of the traffic to the site, you have to make sacrifices.

Filed under: Code