I was searching for a way to prevent being taken to the top of a page after clicking a link with
<a href="#" onclick="foobar()">click me</a>
<a href="#!" onclick="foobar()">click me</a>
#!actually causing the html code to do?
It's telling the browser that when that link is clicked, it should scroll the page to the anchor
!. Because there is no such anchor on the page, the page doesn't move. (Technically, you could have an anchor with the name
! on the page [
! is a perfectly valid HTML
id value]. It's just...you probably don't.)
You create anchors on the page by assigning
id values to elements (or using the outdated
<a name="...">...</a> construct);
hrefs with a fragment identifier (the bit following the
#) tell the browser to load the resource (in your example, it's the current page, which is already loaded) and then scroll down to that anchor. So for instance, if you have
<div id="foo">...</div> on a page, the navigate to
#foo on that page, the browser will scroll down so that that div is showing. When you supply a non-existant anchor, no scrolling is done.