Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Prevent default event behavior - crossbrowser

With almost each javascript event there is a default behavior that is followed after event's been fired. For example, if you click on a link, you can do stuff provided in onclick event, and then you'll be redirected to provided URL.

Not all event behavior can be prevented, usually it can be determined using event.cancelable attribute, but well click event is one of them, that can be prevented.
<a id='test_link' href='http://webcodingeasy.com'>
    Click and stay on this page
</a>
<script type='text/javascript'>
//prevent default event behavior
var prevent_default = function(event){
    if(window.event)
    {
        window.event.returnValue = false;
    }
    else if(event.preventDefault)
    {
        event.preventDefault();
    }
    else
    {
        event.returnValue = false;
    }
};

//add event just for example
var add_event = function(element, type, listener){
    if(element.addEventListener)
    {
        element.addEventListener(type, listener, false);
    }
    else
    {
        element.attachEvent('on' +  type, listener);
    }
};

//example
add_event(document.getElementById("test_link"), "click", 
    function(e){
        prevent_default(e);
        alert("Event prevented");
    }
);
</script>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus