Webeng Webeng - 6 months ago 11
CSS Question

Understanding <a href="#!"

I was searching for a way to prevent being taken to the top of a page after clicking a link with

#
inside the
href
attribute:

<a href="#" onclick="foobar()">click me</a>


and then I came across this simple solution, switching
#
for
#!
:

<a href="#!" onclick="foobar()">click me</a>


There were various other solutions available online using jQuery for instance:

$('.service').click(function(e) {
e.preventDefault();
});


I ended up liking
#!
the most for being so clean BUT I COULDN'T find any documentation anywhere online as to what was actually happening when inserting the
!
in the line of code.

QUESTION:

What is
#!
actually causing the html code to do? Is this a good way to prevent the default action of taking the user to the top of the page, or is this method bad for other reasons? What I'm afraid of is that it might be a hacky method that isn't compatible with some browsers.

Answer

What is #! 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.