Disable scrolling when clicking on a link

I have the following HTML markup, which is just three tabs that, when clicked, display the preloaded text in a div on the page,

<a class="page" id="tab1">This is tab!</a> <a class="page" id="tab2">This is tab 2!</a> <a class="page" id="tab3">This is tab3!</a> 

This jQuery just hides or shows text when you click one of the tabs,

 $(document).ready(function() { $(".page").hide(); $("#tab1").show(); }); $(".page").click(function() { var id = $(this).attr("href"); $(".page").hide(); $(id).show(); }); 

However, if there is a page overflow (i.e. the page scrolls) when I click on one of the tabs, the page automatically scrolls to center the div in the viewport. How can I prevent this?

+6
source share
3 answers

To prevent the page from scrolling on click (after the binding hash), use: Event.preventDefault ()

 $(".page").click(function( evt ) { evt.preventDefault(); // prevents browser default anchor behavior // Other code here.... $(".page").hide(); // HIDE ALL .page $("."+ this.id ).show(); // SHOW RELATED .(id) }); 
+9
source
  <a href="#" class="page" id="tab1" onclick="return false;">This is tab!</a> 

Add return false to all your anchors.

+2
source

This is the default behavior for hash links. You want to prevent the default behavior of the browser, so you should use the event.preventDefault method

 $(".page").click(function( event ) { var $el = $(this), id = $el.attr( "href" ); $(".page").hide(); $el.show(); event.preventDefault(); }); 
0
source

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


All Articles