0

I have a simple script that I am using for a tabbed navigation. It just hides and shows a div. However when I change from tab to tab, the screen always pans back up to the top! Anyone know how to get this to stop? My script is below:

<script type="text/javascript">

$(document).ready(function() {

    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });

});
</script>

2 Answers2

0

I think you need an preventDefault() to your click handler.

This will stop the browser from panning to the top.

Like so:

//On Click Event
$("ul.tabs li").click(function(e) {
    e.preventDefault();
    $("ul.tabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".tab_content").hide(); //Hide all tab content
    var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active content
    return false;
});
urbz
  • 2,663
  • 1
  • 19
  • 29
0

Try changing your click handler to target the <a/> tag rather than the <li/> tag:

//On Click Event
$('ul.tabs li a').click(function() {
    $('ul.tabs li').removeClass('active');
    $(this).closest('li').addClass('active');
    $('.tab_content').hide();
    var activeTab = $(this).attr('href');
    $(activeTab).fadeIn();

    return false; // prevent default action of <a/> element
});

The reason this is happening is that, even though you are returning false on the click handler for the <li/> tag, the <a/> tag's click event bubbles up and is triggered at the same time as it is contained within the <li/> tag. Since there is no click handler preventing the </a> tags' default action, the page jumps to the top – this is assuming the href attributes start with hashes.

I hope this helps!

dSquared
  • 9,725
  • 5
  • 38
  • 54
  • Didnt seem to work but I get what your saying, still unable to solve the jump though. – user2151867 Apr 11 '14 at 16:01
  • Could you update your question with the relevant HTML markup? Also, creating a JSFiddle that showcases the problem would help us determine a solution. – dSquared Apr 11 '14 at 17:35