valemax
valemax

Reputation: 41

page scrolls down when clicking href=#div

When I click on my navigation bar links the page scrolls down. How can I fix this problem? I have a navigation bar with a list of links. Here is the HTML

<ul>
  <li><a href="page.html#1">menu item 1</a></li>
  <li><a href="page.html#2">menu item 2</a></li>
  <li><a href="page.html#3">menu item 3</a></li>                    
</ul>

Here is the code of page.html (a tab menu and a 3 divs with the contents:

<ul class="tabs">
   <li><a href="#1">Tab 1</a></li>
   <li><a href="#2">Tab 2</a></li>
   <li><a href="#3">Tab 3</a></li>
</ul>   

<div id="1" class="tab_content"><p>Content 1</p></div>
<div id="2" class="tab_content"><p>Content 2</p></div>
<div id="3" class="tab_content"><p>Content 3</p></div>    

Here is my jquery code:

var hash1 = location.hash;
var hash2 = hash1.substring(1, 2);

$(".tab_content").hide(); 
$('ul.tabs li:nth-child(' + hash2 + ')').addClass("active").show(); 
$('.tab_content:nth-child(' + hash2 + ')').show();  


$("ul.tabs li").click(function() {
    $("ul.tabs li").removeClass("active"); /
    $(this).addClass("active"); 
    $(".tab_content").hide(); 
    var activeTab = $(this).find("a").attr("href"); 
    $(activeTab).fadeIn(); 
    return false;
});



$(window).on('hashchange', function(){
var hash = window.location.hash;

    elements = $('a[href="' + hash + '"]');
    if (elements.length === 0) {
        $("ul.tabs li:first").addClass("active").show(); 
        $(".tab_content:first").show(); 
    } else {
        elements.click();
        return false;           
    }
});     

Upvotes: 1

Views: 767

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337666

The reason is because href="#1" is telling the browser to scroll the window so that the element with the id of 1 is in view. It's known as a 'bookmark link'. If you do not want this behaviour you need to use preventDefault() on the event in the click handler:

$("ul.tabs li a").click(function(e) {
    e.preventDefault();
});

Upvotes: 2

Related Questions