How to make a hyperlink point to different url based on a read cookie value?


March 2019


340 time



On my website I have links to "contactus.html" page on every single page's menu ( the usual Services, About Us, Contact Us menu) , and each page is made using a dreamweaver template and the menu is only editable in the .dwt template file itself itself .

When the user visits the "index.html" the first time a cookie , called "client-location" is placed with the client's location.

The Desired Outcome:

When the client clicks the Contact Us menu item, I would like to read the client-location cookie and send the user to the right contact page, e.g. contactus2.html or contactus3.html.

I got this from the stackoverflow answer in the link below . Something like this will go in the script.js file

    document.getElementById("contactlink").onclick = function() {
    var clientlocation = readCookie(); // this returns contact1.html, a weblink


Possible Issue:

It is entirely possible that the user, when he/she visits the site the first time goes straight to , say About Us section, and the cookie won't be placed to mention their location at all. In that case I would like to go to contatus1.html , which is a generic contact us page.

And what if the javascript is disabled, then the browser won't even go anywhere upon a click.

I read up online and checked this How to change href of <a> tag on button click through javascript as well, but I am wondering if a) there will be any accessibility issues b) if that is a good approach

4 answers


Well one way to solve this would be using PHP.

Like you said if users browser doesn't support JS or just doesn't have it on it wouldn't work, so a server-side solution might be better.

for example:


function generateLink($location)
  case 0:
   echo '<a href="location1.html">Contact us</a>';
  case 1:
   echo '<a href="location2.html">Contact us</a>';


Can't you set the href of the link to contactus1.html, so that if JS is disabled the link will still work? And as for the cookie not being set, you can just check if clientLocation is null (or blank or whatever your readCookie function returns) and, if so, set the href to contactus1.html.


Surely your "Contact Us" page would have a fixed location? This seems like an unnecessary use for a cookie to me. could be referenced from by linking to ../ContactUs, etc.

Equally you could pull the document root by using location.protocol + '//' + (returning here) and appending the necessary page.

var clientlocation = location.protocol + '//' + + '/ContactUs';

If javascript is disabled, then there is nothing you can do. Javascript will just not execute. This flow can be handled browser-independent by a server-side script.