Saturday 25 July 2015

An Eventful JavaScript

Cross-browser compatibility can be a real pain. Front-end specialists, especially those who aren't making use of some framework or other, can attest to this. The inconsistencies from one browser to another are numerous - sometimes almost overwhelming.

In fact, today I want to talk about one such inconsistency - the Event object. The Event object is what holds information about JavaScript events such as onload, mouseover and so on. For a complete technical reference, follow this link.

We've used Event objects during the web tutorials. And one thing you will find when I handle JavaScript events, is that I mostly have this particular snippet:
if (!e)
{
    var e=window.event;
}


What does this do, and why is it necessary?

Glad you asked! It first checks for an event variable, and if there isn't one, it explicitly creates one.

As for why it's necessary, check out this code snippet.
<script>
document.onmousedown=mousedown;

function mousedown()
{
    alert("x:" + event.clientX + " y:" + event.clientY);
}
</script>


You can copy and paste this into a HTML file, then run it in Chrome. What happens. When you click, does it give you the x and y coordinates of your mouse cursor?

Cool. Now run it in Firefox. Not a peep, right?

That's because in WebKit-based browsers such as Chrome and Safari, event is stored as a Global variable. This isn't true for Firefox, and that's why the JavaScript in Firefox can't detect the Event object.

Here's a list of WebKit-based browsers.

Here's the tweak...
<script>
document.onmousedown=mousedown;

function mousedown(e)
{
   if (!e)
   {
        var e=window.event;
   }

    alert("x:" + e.clientX + " y:" + e.clientY);
}
</script>


Now this will make it work on Firefox in addition to Chrome.

That's all I have for now. Any... objections?
T___T




No comments:

Post a Comment