0

I would like to display a message on the page based on some value appearing in the URL. I have a known list of strings I'm looking for and the corresponding message. I cannot seem to get anywhere with the lookup / messaging. Could anyone pls kindly help? JavaScript only preferred, not jquery. Not that I the difference at this point ;)

Many thanks!

<div id="messagediv"></div>

Sample URLs to test:

<p><a href="#?utm_campaign=SpaComp123">Campaign 1</a>
<p><a href="#?utm_campaign=PoolComp123">Campaign 2</a>
<p><a href="#?utm_campaign=BeachComp123">Campaign 3</a>

<script>
(function () {
    var params = window.location.search.substring(1).split('&'),
    urlParams = {},
    key, val;
    for (var i = 01; i < params.length; i++) {
        urlParams[params.split('=')[0]] = params.split('=')[1];
    }

  // querystring is ?utm_campaign=SpaCamp12458
  // for instance, match URL query value SpaCamp12458 with the nums SpaComp key and show the corresponding text in the messagediv

  var nums = {
        defaultMessage: "Default Message",
        "SpaComp": "Spas",
        "PoolComp": "Recreation",
        "BeachComp": "Outdoors"
    }

    for (var i in nums) {
        if (nums.hasOwnProperty(i)) {
            var found = false;

            for (var j in urlParams) {
                if (urlParams.hasOwnProperty(j)) {
                    if (urlParams[j].indexOf(nums[i]) === 0) {
                        document.getElementById("messagediv").innerHTML = nums[i];
                        found = true;
                        break;
                    }
                }
            }

            if (!found) {
                document.getElementById("messagediv").innerHTML = nums.defaultMessage;
            }
        }
    }

})();

</script>
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
  • 1
    http://stackoverflow.com/a/1961083/1136504 – DannyThunder Apr 07 '14 at 13:28
  • Thank you for your help ADC and DannyThunder. Much appreciated since I'm new posting here. I am able to retrieve the query params. Thopugh not yet figured out how to match that in the "nums" obj. Could you please direct me? Thanks! – user3506876 Apr 07 '14 at 13:38
  • There's a problem here `for (var i = 01; i < params.length; i++) { urlParams[params.split('=')[0]] = params.split('=')[1]; }`. This should be `params[i].split('-')...` (you're not actually using `i` anywhere. – JLRishe Apr 07 '14 at 13:41
  • Thanks JLRishe. What an oversight. I'm using `i` in `nums` and `j` in `urlParams` Would it be correct to change this to `var j = 1; j < params.length; j++` instead since I am attepting to use `urlParams.hasOwnProperty(j)` later? Thanks for your patience with me while I get a grip on why/what everything does. – user3506876 Apr 07 '14 at 14:00
  • Errr that is, Oversight on *my part* -- I wasn't not sure if that was clear in my comment. :) – user3506876 Apr 07 '14 at 17:48

0 Answers0