GoofyBall
GoofyBall

Reputation: 411

Disable Scrolling When Clicking on a Link

I have the following HTML markup, which is just three tabs which when clicked, display pre-loaded 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 simply hides or shows text when one of the tabs are clicked,

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

However, if there is page overflow (i.e. the page is scrollable) when I click on one of the tabs, the page auto-scrolls to center the div in the viewport. How do I prevent this from occurring?

Upvotes: 10

Views: 22878

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 205987

To prevent the page scroll on click (following anchor hash) use: Event.preventDefault()

$(".page").click(function( evt ) {

   evt.preventDefault();       // prevents browser's default anchor behavior

   // Other code here....
   $(".page").hide();            // HIDE ALL     .page
   $("."+ this.id ).show();      // SHOW RELATED .(id)
});

Upvotes: 14

Chuck Norris
Chuck Norris

Reputation: 15190

 <a href="#" class="page" id="tab1" onclick="return false;">This is tab!</a> 

Add return false to all your anchors.

Upvotes: 12

pomeh
pomeh

Reputation: 4902

This is the default behavior for links with hash. What you want is to prevent the default browser behavior, 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();
});

Upvotes: 0

Related Questions