Change #ID URL with jQuery Button

I am trying to create a function where, each time the button is clicked, the identifier at the end of the page URL is added to 1. So,

example.org/page โ†’ (buttonclick) โ†’ example.org/page#1 โ†’ (buttonclick) โ†’ example.org/page#2, etc. etc.

At the moment I have:

var anchor = 0;

$('#bottom-right').click(function() {
  var anchor += 1;
  var anchorurl = "#" + anchor;
  var currenturl = window.location.href;
  var newurl = currenturl.slice(0, -1) + anchorurl;
  window.location.replace(newurl);
});

But this does not work, and I think there is a cleaner solution ...

Thanks in advance.

+4
source share
2 answers

just do it

$('#bottom-right').click(function() {
  window.location.hash = ++anchor;
});

Use the built-in method hash.

+1
source

So basically url contains #. So you can also track this #and get the next number and increase it.

Code example:

var hashValue = window.location.href.substring(window.location.href.indexOf('#')+1);   
window.location.hash = hashValue + 1;
+1
source

All Articles