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.
The href attribute link (short for “Hypertext REFerence”) indicates the relationship between pages to search engines. href is an attribute of the anchor tag and contains two components: The URL (the actual link) and. The clickable text or object that users will see on the page (known as the “anchor text”)
The HREF is an attribute of the anchor tag, which is also used to identify sections within a document. The HREF contains two components: the URL, which is the actual link, and the clickable text that appears on the page, called the "anchor text."
This tag defines a hyperlink, which is used to link from one page to another. And the most important attribute of the a element is the href attribute, which indicates the link's destination.
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); href
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With