Search code examples
jqueryclickhtmlpage-jump

Page jump on span.click()


I have this weird thing happening: when clicking spans in the navigation the content has to switch. Everything works except that when you click a span the page jumps to it (the span will be right at the top then). All I find about page jumps is about anchor tags and return false; but nothing about spans. In my opinion, the switching content can't be to blame because there never is only one div that has display: none (and if that was the case the page should jump to the top instead of jumping to the span, right?) Preventing any actions doesn't seem to work on spans.

$("#subnavi span").click(function(){
    $("#inner-content div:visible").animate({height: "toggle", opacity: "toggle"}, "slow");
    $("#content-"+this.id).animate({height: "toggle", opacity: "toggle"}, "slow");
    $("#subnavi span").attr("class", "");
    $(this).attr("class", "active");
});

If the explanation was confusing, go here: http://gaming-siblings.com/v2.0/#news and click Statistics in the navigation on the left. The page will jump down to the span you just clicked and scroll back a little due to the div's height. Why does it jump to the span?

It's probably not weird but reasonable. I just don't get it :-)

I've tried this for 2 days now, taking breaks from it because that mostly helps but not this time.

Any ideas / solutions? As mentioned return false; or preventDefault() didn't work when I tried (because it's spans I guess).


Solution

  • I spotted this extra line in your click() function:

    document.location.hash = "#" + this.id;
    

    This is the cause of the 'jump'—you're adding the hash to the URL of the page so the page will automatically scroll to that anchor (in this case, it will scroll to the element that was clicked since you're appending its id).

    There isn't really a workaround that I know of that won't reload the page completely. Your best bet is to just use separate pages or not use the hash at all.