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









Stop JavaScript event bubbling

JavaScript performs event bubbling in the sense that when an event like omouseover, onclick, etc occurs in the child controls it is raised for the containing controls also till the outermost parent containing control. Suppose we have a HTML structure like this

   1:  <div id="blockDiv"> 


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


   3:              </a>


   4:       </span> 


   5:        <p> 


   6:              Nothing much


   7:        </p> 


   8:   </div>




 



where Div is the parent control containing span which further contains a (link). Now when onmouseout occurs on a (link) after we take our mouse pointer out of it, 2 more events fire at the same time. onmouseout of span as well as onmouseout of div. This is the called event bubbling and the default behaviour of JS. If you have some script written on these 2 mouseouts, it will unnecessarily fire.



 



How to stop this: Its quite easy to via the stopPropagation() method in JS



function aout (event){

//Do something on a link mouseout

event.stopPropagation();

}