Sometimes we want to perform some javascript actions using link but don’t want to jump to another page. We can do this using event object.

For example we have a link say:

<a onclick="alert('Hello');" href="http://www.example.com/">Say Hello</a>

Clicking this link will show an alert saying “Hello” but will then move to http://www.example.com/.

To prevent this behavior first we will capture the eventobject and use its method preventDefault():

<a onclick="alert('Hello');event.preventDefault()" href="http://www.example.com/">Say Hello</a>

The above will work fine in Firefox, Chrome, Safari and Opera but does not work in IE instead IE provides a property of event object named returnValue, setting this to false resolves the issue:

<a onclick="alert('Hello');event.returnFalse()" href="http://www.example.com/">Say Hello</a>

Again this works fine with IE, Chrome, Safari, Opera but does not work with Firefox. So the right way is to take care of both i.e. IE and Firefox :

<a href="http://www.example.com/" onclick="alert('Hello');if(event.preventDefault) event.preventDefault(); else event.returnValue = false;" >Say Hello</a>

or Simply

<a onclick="foo(event)" href="http://www.example.com/">Say Hello</a>
<script type="text/javascript">// <![CDATA[
     function foo(e){         alert("Hello");         if(e.preventDefault)            e.preventDefault();         else            e.returnValue = false;     }
// ]]></script>
Tagged with:
 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">