Saturday, January 28, 2012

That jquery click event and moving viewport problem

Sometimes certain combinations of attributes and values on a DOM element conspire to make you look stupid. In this case, a jQuery click function attached to an anchor tag with a href attribute.
<a href="#" class="reply-action">  
      <span>  
         <i></i>  
             Reply  
         </span>  
      </a>  
</span> 
And the jQuery is pretty straight-forward. The anchor tag when clicked will just toggle a div.replies to show or hide.
$('.reply-action').click(function () {
 $('.replies').toggle();
})
At this point, all things work. The replies div slide up and down as described by the jQuery toggle function. Normally this isn't a problem when you run this code at very top of the browser viewport. "Top of the browser viewport" simply means that the page hasn't scrolled down. The "moving viewport" problem happens when you run the click function when you're at bottom of the page. The click function keeps forcing the viewport to move to the top. Its annoying as hell. Fortunately the solution is simple. So simple in fact it made me go *FACE PALM*. The root of the problem is the the anchor href attribute set to "#". So by just changing the href attribute to something else like javascript:void(0) or just simply delete it, you fix the problem.
<a href="javascript:void(0)" class="reply-action">  
      <span>  
         <i></i>  
             Reply  
         </span>  
      </a>  
</span> 
It took me about a day to figure it out after trying to use overly complex jQuery like event and mouse APIs. Talk about being given the runaround.

No comments:

Post a Comment