Prevent the default action for an event

by Rekha 2008-03-14 08:51:38

Hi

There are many occasions when you have to override the default action of an event. For example, when a link is clicked, you want a popup to open(desired action) rather than going to the the page in the href attribute(default action).Functions like e.stopPropagation and e.preventDefault will help you to do so.

Example:

<script>
function openPopup() {
var url = this.href;
window.open(url, "popup_id", "scrollbars,resizable,width=300,height=400");
return false;
}

window.onload = function() {
document.getElementById("popup").onclick=openPopup;
}
</script>
...


That does what we need - but we cannot relay on the return false method for preventing the default action. Giving this code will exit the function - so if there is more to do in the function, this code cannot be used.we need something more drastic.

<script>
function openPopup(e) {
if(!e) var e = window.event;
var url = this.href;
window.open(url, "popup_id", "scrollbars,resizable,width=300,height=400");

//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;

//e.stopPropagation works only in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}

window.onload = function() {
document.getElementById("popup").onclick=openPopup;
}
</script>
...


Explanation:
We get the details of the event in a variable called 'e'.
Internet Explorer:

//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;

This will cancel the bubbling process. So no further actions will take place due to this event.

e.returnValue = false;

Remember the return false method of preventing the action? This is another way of doing the same thing - but without exiting the function.
Firefox/Other Browsers:

//e.stopPropagation works only in Firefox.
if (e.stopPropagation) {

First use object detection to see whether the user is using Firefox - as Internet Explorer don't support the e.stopPropagation() function. So only Firefox browsers will execute the code in the if condition.

e.stopPropagation();

Stop the capturing process(reverse of the bubbling process).

e.preventDefault();

Prevents the default action from taking place.
1729
like
0
dislike
0
mail
flag

You must LOGIN to add comments