How to add #hash clicking to an element
21,810
Solution 1
Using plain old vanilla JS:
window.location.hash='example';
Solution 2
There's two ways, either you use javascript, where you have access to the window.location.hash, or you bind your click event to an <a href="#example">
, and prevent default on click, or think it's cool when your page goes up to the top, and the hash should appear in the browser adress bar.
Solution 3
Reviving this thread, nowadays you can use history API
, works the same as above but also avoids automatically scroll to an id, giving you complete control of what you want to do with that hash:
window.history.pushState({}, "Example Title", "#example");
Author by
markzzz
Updated on May 18, 2020Comments
-
markzzz about 4 years
When I open my page at http://www.mywebsite.com/ where I have this jQuery code :
$('#locSlideButton2').click(function() { });
I'd like, clicking on the
locSlideButton2
element, add an hash (such as #example) to the url, without make any redirect.How can I do it?
-
honk31 over 9 yearsa button inside an a element isn't valid html. see here
-
TwystO over 5 yearsOk, just copy/paste this piece of code into the W3C HTML validator and check it.
<!doctype html><html lang="en"><title>Test</title><a href="#yourhash"><button id="locSlideButton2">Click me.</button></a></html>
You'll see it's not valid html.