I have created a tabbed interface, utilizing page anchors. This is a problem because by default, a browser navigates to the anchor when a link linking to it is clicked on the same page:
showTab = function(tabName) {
tabName = tabName.replace(" ", "_"); //Fix space in tab name so that JS can use it.
$(".tab_selected").addClass("tab");
$("#p_" + document.querySelector(".tab_selected").id).hide();
$(".tab_selected").removeClass("tab_selected");
$("#" + tabName).addClass("tab_selected");
$("#p_" + tabName).show();
location.hash = tabName;
document.title = tabName.replace("_", " ") + " | AnED";
}
//if (location.hash.length < 1)
// showTab("Information");
body {
height:1200px;
}
.page_tabgroup {
display:table;
margin:0 auto;
width:auto;
margin-top:50px;
border-radius:4px;
background-color:#FFF;
border:solid 2px rgba(0, 120, 255, 0.8);
}
.page_tabgroup > a {
text-decoration:none;
border:none;
}
.page_tabgroup > .tab {
display:table-cell;
padding:10px 20px 10px 20px;
color:rgba(0, 120, 255, 0.8);
}
.page_tabgroup > .tab:hover, .primary_page > .page > .page_tabgroup > .tab_selected:hover {
background-color:rgba(0, 120, 255, 0.95);
border:inherit solid rgba(0, 120, 255, 0.6);
color:#FFF;
}
.page_tabgroup > .tab_selected {
display:table-cell;
padding:10px 20px 10px 20px;
color:#FFF;
background-color:rgba(0, 120, 255, 0.8);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page_tabgroup">
<a href="javascript:showTab('Information')" class="tab tab_selected" id="Information">Information</a>
<a href="javascript:showTab('Course_Dates')" class="tab" id="Course_Dates">Course Dates</a>
</div>
In the above example, the browser automatically scrolls down so that the anchor element is at the top. This is annoying behaviour, but unsurprising. I tried using preventDefault()
as in this answer to Avoid window jump to top when clicking #-links, however it doesn't have any effect whatsoever. This is likely because I am not using a click handler (the function is directly executed via a javascript:showTab
link).
Using click handlers blocks the showTab
function from executing entirely, and appending it with showTab(e.id);
creates a Cannot read property 'replace' of undefined
error for line 2 of showTab
:
$(".tab_selected").click(function(e) {
e.preventDefault();
});
$(".tab").click(function(e) {
e.preventDefault();
});
Is it possible to block the default anchor behaviour outside of a click handler? If not, how can I fix this?