1

I want to display a div only if the user types in a query in the URL. I have the following code:

HTML

<div id="hidden" style="width:100%;height:20%;background-color:blue;display:none;">
Hidden Div Contents
</div>

JS

$(function() {
  var params = {};
  var ps = window.location.search.split(/\?|&/);
  for (var i = 0; i < ps.length; i++) {
        if (ps[i]) {
              var p = ps[i].split(/=/);
              params[p[0]] = p[1];
        }
  }
  var divToShow = params.from;
  $('#'+divToShow).show();
});

JSFiddle - http://jsfiddle.net/b48zL/

Link to see it works - http://jsfiddle.net/b48zL/show/?from=hidden


Problem

It appears to function correctly on the fiddle but on my server it renders the div with or without the query with the text from the script printed in the div.

ie, it looks as though I coded:

<div>$(function() { ... ...$('#'+divToShow).show();});</div>

Why?

redditor
  • 4,196
  • 1
  • 19
  • 40

1 Answers1

1

Your JS code does not decode URL parameter values. Following code decodes URL parameters correctly

// based on https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
})();

if(urlParams.from) $("#hidden").show();

Fixed JSFiddle

Community
  • 1
  • 1
Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55