I\'ve got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when
Example with nice scrolling to answer content:
$("#question_title").click(function(){
var $answer=$("#answer");
$answer.slideDown();
$.scrollTo( $answer, 800 );
return false;
});
I'm used jQuery scrollTo plugin.
You can do it very simple:
Just add !
in the end of your href
:
<a href="#!" id="myID">Myquestion</a>
The alternative jQuery ways are:
$("#myID").click(function(e) {
e.preventDefault(); // one way
return false; // second way prevent default click action from happening
});
Actually, the easiest way to do this is to remove the href attribute from your anchor tag. As of HTML5, anchor tags don't need to include href attributes to be semantic.
So
<a id="myID">Myquestion</a>
instead of
<a href="#" id="myID">Myquestion</a>
This works in IE8+, Chrome, and Firefox. Note that :link css styles won't apply to anchor tags that don't include href attributes.
If you need the href attribute and/or IE7 compatibility, then
$("#myID").click(function(e) {
if(e.preventDefault)
e.preventDefault();
else
e.stop();
});
is probably the best way to go.
$('a').click( function() {
if ($(this).attr("href") == window.location.hash) {
event.preventDefault()
}
});
$("#myID").click(function(e) {
if(e.preventDefault)
e.preventDefault();
else
e.stop();
});
e.preventDefault()
alone did not work in older versions of IE.
Don't use A tags for tasks that are not navigation-related. It is not semantic markup, and doesn't degrade gracefully. Use buttons instead.