This happens because href="#"
tells the browser to jump to the top of the page when the link is clicked.
You can prevent that default action by returning false
from your onclick
attribute handler:
<a href="#" onclick="toggle_visibility('foo');return false;">School Area</a>
But as you're using jQuery, consider attaching that event handler dynamically (or even using event delegation), and then use preventDefault
:
<a href="#" class="toggle-vis" data-visibility="foo">School Area</a>
then here's a delegated handler:
$(document.body).on("click", ".toggle-vis", function(e) {
e.preventDefault();
toggle_visibility(this.getAttribute("data-visibility"));
});
note how the data-visibility
attribute controls what we toggle.
You'll get people telling you to change this line:
toggle_visibility(this.getAttribute("data-visibility"));
to
// Only do this if you understand what `data` does
toggle_visibility($(this).data("visibility"));
but data
is not just an accessor for data-*
elements, it does more (and less) than that. If you don't need the features that work sets up, there's no need to wrap the element in a jQuery instance and call data.
But if you prefer More jQuery™:
toggle_visibility($(this).attr("data-visibility"));
also works.