markzzz
markzzz

Reputation: 47945

How to add #hash clicking to an element

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?

Upvotes: 13

Views: 24522

Answers (4)

Wenceslao Negrete
Wenceslao Negrete

Reputation: 556

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");

MDN on History API

Upvotes: 1

HackerManiac
HackerManiac

Reputation: 243

simply wrap #locSlideButton2' with` like this

<a href="#yourhash"><button id="locSlideButton2">Click me.</button></a>

This will do

Upvotes: -4

adeneo
adeneo

Reputation: 318212

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.

Upvotes: 7

Some Guy
Some Guy

Reputation: 16210

Using plain old vanilla JS:

window.location.hash='example';

MDN on window.location

Upvotes: 51

Related Questions