I’m making a simple navigation with jQuery that loads content panes by showing or hiding them on the page. I am using anchor tags to determine which pane to show. I also use a “ready” function to show the #hash element when the page is loaded. Pretty basic:
$(document).ready(function() {
$('#video_form_content > div').hide();
var showTab = window.location.hash || "#basic-info";
$(showTab).show();
}
$('#video_form_tabs li').on('click', function() {
$('#video_form_content > div').hide();
var target = $(this).children('a').attr('href');
$(target).show();
})
What’s happening, though, is that when the elements are clicked, the page jumps to the top of the target div. I don’t want this jump, but I do want to keep the default functionality of the anchor tag in the sense that I want the hash added to the URL so that refreshing would reopen the same tab.
Here’s what I’ve tried
- Adding
$(window).scrollTop(0)to the click event. I thought it might, but this event fires before the actual navigation of the anchor element, so it’s immediately undone. - Adding
$(window).scrollTop(0)to$(document).ready()However, this listener is not fired when clicking an anchor for the same page. - Adding
window.location.hash = targetorwindow.location.href = targetto the click event. However, this still causes the resubmission of the page, and it still “jumps”. - Adding
return falseto the function. This prevents adding the hash to the URL, which is highly preferred.
This is really baffling me, and any help would be much appreciated.
Identify your target
divs with things like#basic-info-TAB, then add"-TAB"to thetargetvariable.