When I have a link that is wired-up with a jQuery or JavaScript event such as:
<a href="#">My Link</a>
How do I prevent the page from scrolling to the top? When I remove the href attribute from the anchor the page doesn't scroll to the top but the link doesn't appear to be click-able.
When calling the function, follow it by
return false
example:Create a page which contains two links- one at the top and one at the bottom. On clicking the top link, the page has to scroll down to the bottom of the page where bottom link is present. On clicking the bottom link, the page has to scroll up to the top of the page.
You need to prevent the default action for the click event (i.e. navigating to the link target) from occurring.
There are two ways to do this.
Option 1:
event.preventDefault()
Call the
.preventDefault()
method of the event object passed to your handler. If you're using jQuery to bind your handlers, that event will be an instance ofjQuery.Event
and it will be the jQuery version of.preventDefault()
. If you're usingaddEventListener
to bind your handlers, it will be anEvent
and the raw DOM version of.preventDefault()
. Either way will do what you need.Examples:
Option 2:
return false;
In jQuery:
So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:
If you're using raw DOM events, this will also work on modern browsers, since the HTML 5 spec dictates this behaviour. However, older versions of the spec did not, so if you need maximum compatibility with older browsers, you should call
.preventDefault()
explicitly. See event.preventDefault() vs. return false (no jQuery) for the spec detail.Returning false from the code you're calling will work and in a number of circumstances is the preferred method but you can also so this
When it comes to SEO it really depends on what your link is going to be used for. If you are going to actually use it to link to some other content then I would agree ideally you would want something meaningful here but if you are using the link for functionality purposes maybe like Stack Overflow does for the post toolbar (bold, italic, hyperlink, etc) then it probably doesn't matter.
Try this:
For Bootstrap 3 for collapse, if you don't specify data-target on the anchor and rely on href to determine the target, the event will be prevented. If you use data-target you'll need to prevent the event yourself.