Wednesday, May 20, 2009

Stop hyperlink href browse

Suppose a scenario comes where you have a Javascript onclick event defined on a hyperlink which performs some action and you want to prevent the hyperlink to browse the URL specified in the href. By default, first onclick script is executed then hyperlink takes you to the href webpage. If you want to suppress the later, the technique to do this is using jQuery. In the post, I assume you know ABC of jQuery and know how to include it and refer it.

 

Now take example of the following markup

<span>


<a href="http://www.example.com/" id="lnk">The quick brown fox jumps over the lazy dog. </a>


</span>




And you have jQuery event hooked to it and you want only that to execute but not the link browsing. Here's the code for that which achieves it through the preventDefault() method.



<script type="text/javascript">
$(document).ready(function() {
$('#lnk').click(function(event) {
alert('It wont take you to the webpage');
event.preventDefault();
});

});
</script>



 



I have described a similar scenario on event bubbling in my previous post









No comments: