Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a click on a '#' link from jumping to top of page?

People also ask

How do you stop a click event in CSS?

You can't prevent click with css, you must use javascript. The dislpay:none only hide a element, in this case, a div.

How do I stop a div from clicking?

To disable clicking inside a div with CSS or JavaScript, we can set the pointer-events CSS property to none . Also, we can add a click event listener to the div and then call event. preventDefault inside.

How do I stop a web page from scrolling to the top when a link is clicked?

To stop a web page from scrolling to the top when a link is clicked that triggers JavaScript, we call preventDefault in the link's click handler. document. getElementById("#ma_link").


So this is old but... just in case someone finds this in a search.

Just use "#/" instead of "#" and the page won't jump.


In jQuery, when you handle the click event, return false to stop the link from responding the usual way prevent the default action, which is to visit the href attribute, from taking place (per PoweRoy's comment and Erik's answer):

$('a.someclass').click(function(e)
{
    // Special stuff to do when this link is clicked...

    // Cancel the default action
    e.preventDefault();
});

you can even write it just like this:

<a href="javascript:void(0);"></a>

im not sure its a better way but it is a way :)


Solution #1: (plain)

<a href="#!" class="someclass">Text</a>

Solution #2: (needed javascript)

<a href="javascript:void(0);" class="someclass">Text</a>

Solution #3: (needed jQuery)

<a href="#" class="someclass">Text</a>
<script>
$('a.someclass').click(function(e) {
    e.preventDefault();
});
</script>

You can use event.preventDefault() to avoid this. Read more here: http://api.jquery.com/event.preventDefault/.