Preventing the top of the page from clicking on the link

How can I prevent the page from β€œjumping” every time I click a link? For example, I have a link somewhere in the middle of the page, and when I click on it, the page jumps up.

+4
source share
3 answers

Suppose this is your HTML for reference:

<a href="#something" id="some_id">Some link goes somewhere...</a> 

If you are using jQuery , try like this:

 $(document).ready(function() { $('a#some_id').click(function(e) { e.preventDefault(); return false; }); }); 

Demo at: http://jsfiddle.net/V7thw/

If you are not using jQuery drugs, try this pure JavaScript DOM :

 window.onload = function() { if(document.readyState === 'complete') { document.getElementById('some_id').onclick = function(e) { e.preventDefault(); return false; }; } }; 
+5
source

Is the anchor href="#" ? You can set it instead of href="javascript:void(0);" .

If you are going to prevent by default, use instead:

event.preventDefault ? event.preventDefault() : event.returnValue = false;

+4
source

It will move up if you set the href property to the # link, as it is looking for the anchor tag. Just leave the href property and it will not go anywhere, but it will no longer look like a link (and be sure to handle click even in javascript, otherwise it really will not be very useful).

Another option is to handle the click in javascript and inside the event handler, undo the default action and return false.

  e.preventDefault(); return false; 
+1
source

Source: https://habr.com/ru/post/1440189/


All Articles