taylor
taylor

Reputation: 509

Checking and adding on to URL hash using window.location.hash

Right now if I have multiple links using:

Options 1:
<a href="javascript:;" onClick="window.location.hash+='A'">Option A</a>
<a href="javascript:;" onClick="window.location.hash+='B'">Option B</a>
<a href="javascript:;" onClick="window.location.hash+='C'">Option B</a>

Options 2:
<a href="javascript:;" onClick="window.location.hash+='1'">Option 1</a>
<a href="javascript:;" onClick="window.location.hash+='2'">Option 2</a>
<a href="javascript:;" onClick="window.location.hash+='3'">Option 3</a>

Options 3:
<a href="javascript:;" onClick="window.location.hash+='X'">Option X</a>
<a href="javascript:;" onClick="window.location.hash+='Y'">Option Y</a>
<a href="javascript:;" onClick="window.location.hash+='Z'">Option Z</a>

Whenever clicking any of these, it will keep adding to the URL. Is there a way to check if a current hash already exists (ie. if third character in hash string, then replace with current hash). Any help would be great thanks! I'm trying to accomplish an end result which looks like below even if the user went back and forth between selecting options:

http://mydomain.com/question-page#A3Y 

Upvotes: 4

Views: 9188

Answers (1)

kennypu
kennypu

Reputation: 6061

change it to += to concatenate:

window.location.hash+='A';

I would do something like the following:

first, create variables for each of the possible options:

var option1 = "";
var option2 = "";
var option3 = "";

next, create a function that will set the hash:

function generateHash() {
  window.location.hash = option1 + option2 + option3;
}

finally, just set each of those options in the onclick event, as well as generating the hash:

<a href="javascript:;" onClick="option1 = 'A'; generateHash();">Option A</a> 
 ...
<a href="javascript:;" onClick="option2 = '1'; generateHash();">Option 1</a>
...
<a href="javascript:;" onClick="option3 = 'X'; generateHash();">Option X</a>

Upvotes: 3

Related Questions