Pass URL Parameters to Button

I have another reusable solution if anyone is interested. The mechanism is the same, just a bit cleaner. It appends ALL search params, not just some.

In the example I’m attaching all search params to two buttons: one with id sign-in-btn and another with id sign-up-bnt.

<script type="text/javascript">
  window.onload = function () {
    const signInBtn = document.getElementById("sign-in-btn");
    appendUtmsToButton(signInBtn);

    const signUpBtn = document.getElementById("sign-up-btn");
    appendUtmsToButton(signUpBtn);
  };

  function appendUtmsToButton(button) {
    // Read utm params from url:
    const pageSearch = window.location.search;
    const urlParams = new URLSearchParams(pageSearch);

    // Build new params for the button combining the button' params with the utm:
    const buttonUrl = new URL(button.href);
    let newButtonParams = new URLSearchParams(buttonUrl.search);

    urlParams.forEach(function(value, key) {
      newButtonParams.append(key, value);
    });

    // Build new url for the button attaching the params:
	buttonUrl.search = "";
    const newSearchString = newButtonParams.toString();
    buttonUrl.search = newSearchString;
    const newHref = buttonUrl.toString();

    // Replace the button's url:
    button.href = newHref;

    // For debugging log final button link to console:
    // console.log(button.href);
  };
</script>
2 Likes