Sunday, March 7, 2010

Javascript stop event bubbling and stop browser default action

// stop event bubbling
function stopBubble(e) {
if( e && e.stopPropagation ) {
e.stopPropagation();
} else {
//IE
window.event.cancleBubble = true;
}
}

// stop browser default action, i.e, clicking an html link will open up that link.
function stopDefault(e) {
if( e && e.preventDefault )
//Other than IE
e.preventDefault();
else
//IE
window.event.returnValue = false;
}

function loadLi() {
var li = document.getElementsByTagName("li");
//alert(li.length);
for ( var i = 0; i < li.length; i++ ) {
li[i].onmouseover = function() {
this.style.backgroundColor = 'blue';
};

li[i].onmouseout = function() {
this.style.backgroundColor = 'white';
};
}
}

function loadAnchor() {
var anchor = document.getElementsByTagName("a");
for ( var i = 0; i < anchor.length; i++ ) {

anchor[i].onmouseover = function(e) {
this.style.backgroundColor = 'red';
stopBubble(e);
};

anchor[i].onmouseout = function(e) {
this.style.backgroundColor = 'white';
stopBubble(e);
};

anchor[i].onclick = function(e) {
iframe.src = this.href;
return stopDefault(e);
}
}
}

No comments:

Post a Comment