KaisarCode

Scripting 4 freeDOM



JavaScript Prevent Default

by KaisarCode

function preventDefault(e){
    //prevent event's default action
    if(window.event) e=window.event;
    if(e.preventDefault){e.preventDefault()}else{e.returnValue=false};
}

As I've promised, we're gonna start analyzing the functions that we've seen before, inside the JavaScript Rotate library. Some of them are pretty silly, other ones are not, but all of them help us to understand how certain routines works using JQuery.

Other comment that I want to add is that from now on I'll try to put the main code el at the top of the article, and the explanation below, to not force the reader to pass through all the text lines if they just want a quick solution for their own job.

Well, said that, today is the turn of the preventDefault method, to start with something easy.

Prevent Default is a JavaScript native method that allows us to block a default action executed after an event, for example, when you click a link, this redirects the browser to the URL specified in the href attribute.

Using preventDefault

In true friendly browsers, having for example an <a> element, a preventDefault is executed in the following way:

HTML
<a id="anchor" href="http://kaisarcode.com">kaisarcode</a>
JS
var anchor=document.getElementById("anchor");
anchor.onclick=function(e){
    e.preventDefault();
};

(I'm not going to use event listeners untill we get to that part, this note goes for the annoying douchebags that complains about everything)

But, sadly, in IE8 this doesn't works at all, because it arranges the events like shit... and sadly2, lots of clients still asks for IE8 support.

The thing is that IE8 arrange all events in a single global property, called window.event, and this sucks hardly. So, in the code that we've seen at the top, we play with the different ways to prevent the default event behavior in a cross browser way.

How?

  • We create an autonomous preventDefault function, that receives an event as parameter.
  • If the property window.event exists, we assign its value to the parameter variable.
  • We check if the variable "e", now has the preventDefault event.
  • If it has it, is executed, if not, we go for the IE's manner, which is e.returnValue=false.