jQuery HTML Anchor Tag Progressive Enhancement
I have jQuery that I have written that is supposed to find a particular <a>
tag and change its behavior. Before jQuery loads, the <a>
tag has an href attribute that points to another page. I am using jQuery to change the behavior of the <a>
tag so that rather than directing the browser to load that other page, it instead runs javascript when clicked that loads content dynamically in a <div>
that is positioned at the location of the mouse pointer.
So, for example, I have the following:
The jQuery I have running does the following:
<a class="funk" href="http://example.com/page2.html">Link</a>
<div class="hidden bubble">Load this instead.</div>
$(document).ready(function(){
$('.bubble').hide()
$('.bubble').removeClass('hidden');
$('.funk').attr('href', '#');
$('.funk').click(function(e){
$('.bubble').show();
})
})
The problem I have is: Whenever the user clicks the link, the brows开发者_运维问答er acts on the href="#"
attribute and brings scrolls the browser to the top of the page. What is the most "correct" way to make my site so that the browser does not scroll at all, but instead merely executes the jQuery code that I have written for the click event?
Let the 'click' function return false
. That cancels the event, and the browser doesn't follow the link. In this case, you can even let the href
attribute at its original value.
$('.funk').click(function(e){
$('.bubble').show();
return false;
//--^
})
To be on the save side, you can explicitly cancel the event:
e.preventDefault(); // no default action
e.stopPropagation(); // event doesn't bubble up or down in the DOM
Add this to your click function:
$('.funk').click(function(e){
e.preventDefault();
e.stopPropagation();
$('.bubble').show();
});
This will do what is implied by the method names.
Call e.preventDefault()
in the click handler.
http://api.jquery.com/event.preventDefault/
精彩评论