-2

I'm working on a project where the user would like to be able to add either "?2yr" or "?4yr" to the end of the URL, but when the user then clicks to another page pass that query along as well.

For example, http://example.com/index.html?2yr is the home page, but when you click say contact it would be http://example.com/powerful_predictors.html?2yr.

I've tried doing the following:

var _url = window.location;


if(window.location.href.indexOf("2yr") >- 1) {
    console.log("your url contains the 2yr");

} else if(window.location.href.indexOf("4yr") >-1){ 
    console.log("your url contains 4yr");
}

How might I add the "?2yr" or "?4yr" when the user clicks a URL to go to another page?

kirdua
  • 85
  • 1
  • 2
  • 8

2 Answers2

1

There are a couple of solutions to the issue, but first, I'd recommend a better parameter parser for your JavaScript code.

This is a much more robust solution

That in place, you have two solutions.

One is to, on page start, run a loop and update all of the a#href properties with the HTML parameters you retrieved earlier. This works, if you are serving static content. If you have any dynamic content, it quickly falls apart.

So, the next solution is to set up a delegated event -- basically, you attach a click event to the body element, then check what the actual element to be clicked on was.

You can learn more here.

Community
  • 1
  • 1
Jeremy J Starcher
  • 21,760
  • 5
  • 48
  • 70
0

You could loop through all your anchor tags, and modify the property href to add the querystring:

document.addEventListener('DOMContentLoaded', function() {
  [].forEach.call(document.querySelectorAll('a[href]'), function(el, i) {
    el.href = el.href + location.search;
  });
});
Buzinas
  • 11,017
  • 1
  • 30
  • 56
  • Hi Buzinas, I tried your code but it did not append the URL to include the query string. – kirdua Sep 29 '15 at 18:19
  • @kirdua sorry, it was a typo. I've fixed my answer. Take a look at the [pluker](http://plnkr.co/edit/DTxVP7NgJKm708m6yVMc?p=preview) I've created for you. – Buzinas Sep 29 '15 at 18:33
  • thanks. Is there a way for the query string to be added via the address bar. My client wants to just add "?2yr" or "?4yr" through the address bar and that would then get passed to all other hrefs. – kirdua Sep 29 '15 at 18:37
  • The code in answer will already do that! Try to open [this link](http://run.plnkr.co/ESdRVGYPlDf0NUzN/page.html?4yr), and then change the address bar to `?2yr` and see what happens to the links. :) – Buzinas Sep 29 '15 at 18:45
  • But if you want to show the links in the status bar, you should change the `href` attribute, instead of the property, e.g: `el.setAttribute('href', el.getAttribute('href') + location.search);` – Buzinas Sep 29 '15 at 18:51