Search code examples
javascriptcountdown

I want to add a countdown to a webpage using an parameter from a link


We are using niftyimages to add countdowns on our emails and would like to use a countdown on our webpage. We would like to make it personalized to the individual when they click on a link from the email to the landing page.

So if we have a link: www.webpage.com?dt=2021-06-01

I tried this code:

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

  // stuff after # is not part of query string, so get rid of it
  queryString = queryString.split('#')[0];

  // split our query string into its component parts
  var arr = queryString.split('&');

  for (var i = 0; i < arr.length; i++) {
    // separate the keys and the values
    var a = arr[i].split('=');

    // set parameter name and value (use 'true' if empty)
    var paramName = a[0];
    var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];

    // (optional) keep case consistent
    paramName = paramName.toLowerCase();
    if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();

    // if the paramName ends with square brackets, e.g. colors[] or colors[2]
    if (paramName.match(/\[(\d+)?\]$/)) {

      // create key if it doesn't exist
      var key = paramName.replace(/\[(\d+)?\]/, '');
      if (!obj[key]) obj[key] = [];

      // if it's an indexed array e.g. colors[2]
      if (paramName.match(/\[\d+\]$/)) {
        // get the index value and add the entry at the appropriate position
        var index = /\[(\d+)\]/.exec(paramName)[1];
        obj[key][index] = paramValue;
      } else {
        // otherwise add the value to the end of the array
        obj[key].push(paramValue);
      }
    } else {
      // we're dealing with a string
      if (!obj[paramName]) {
        // if it doesn't exist, create property
        obj[paramName] = paramValue;
      } else if (obj[paramName] && typeof obj[paramName] === 'string'){
        // if property does exist and it's a string, convert it to an array
        obj[paramName] = [obj[paramName]];
        obj[paramName].push(paramValue);
      } else {
        // otherwise add the property
        obj[paramName].push(paramValue);
      }
    }
  }
}

return obj;
} 

console.log(getAllUrlParams("https://img1.niftyimages.com/q24/9jso/fjad?dt=2021-07-21&format=yyyy-MM-dd"));

The image from niftyimages is <img src="https://img1.niftyimages.com/q24/9jso/fjad?dt=2021-07-21&format=yyyy-MM-dd" />

I've isolated dt=2021-06-01, what do I do to replace the "dt=2021-07-21" part in the image url?


Solution

  • Just to keep your code uber simple you could add an id to your img tag like this:

    <img id="niftyImg" src="nifty.com?dt=2021-05-02" />
    

    and then do something like this for your JS:

    document.addEventListener("DOMContentLoaded", function(event){
      var url = new URL(window.location.href);
      var dt = url.searchParams.get("dt");
      var element = document.getElementById("niftyImg");
      var regex = /[0-9]+-[0-9]+-[0-9]+/gm;
      element.src = element.src.replace(regex, dt);
    });
    

    What this does is waits for the DOM to finish loading then grabs the query parameter off the url, finds your image tag on the page and replaces the date in your src attribute with the one in the url. There's probably slicker ways of doing the regex in case you might have something other than a date there but this will likely get you in the ballpark of what you're trying to do. There may be a flash of the image on page load of the old date but then once the javascript executes the image will update to the new date. If you don't want that flash you would want to do something server-side before the page is rendered if that's an option.