Evaluating Javascript URL Parameter

So i have posted the code but basicly i want to add a url parameter and have javascript be able to grab and read it.  So this part works, i can get the parameter and write it out with

document.write("type=" + g_querystring["type"] + "<br>");

But what i want to do is run some conditional statements to do different things specifically hide the div with the id of menu if the parameter is a certain thing.

So if i have ?type=arth on my url then the menu div should be hidden

if(g_querystring["type"] == "arth")
{
  var mydiv=document.getElementById("menu");
  mydiv.style.visibility="hidden";
  mydiv.style.display="none";
  document.write("Yea worked");
}

The hidding the div part etc should be fine but the condition i cant get to evaluate as true or correct or in other words even if i have ?type=arth on my url the line of code if(g_querystring["type"] == "arth") doesnt seem to evaluate as true and run the options there
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
 
  <script type="text/javascript">
function parseQueryString()
{
var obj = new Object();
 
var nvpairs = location.search.substring(1).split("&");
 
for (var idx = 0; idx < nvpairs.length; idx++)
{
var tokens = nvpairs[idx].split("=");
 
obj[unescape(tokens[0])] = tokens.length == 2 ?
unescape(tokens[1]) : undefined;
}
 
return obj;
}
 
var g_querystring = parseQueryString();
 
document.write("type=" + g_querystring["type"] + "<br>");
 
// Iterate through all name/value pairs
 
if(g_querystring["type"] == "arth")
{
  var mydiv=document.getElementById("menu");
  mydiv.style.visibility="hidden";
  mydiv.style.display="none";
  document.write("Yea worked");
}
</script>
</head>
 
<body>
<div id="menu">I am the menu button</div>
 
<div id="body">I am the body information </div>
 
<div id="footer">I am the footer information</div>
 
 
</body>
</html>

Open in new window

LVL 4
Brant SnowAsked:
Who is Participating?
 
jwmcpeakConnect With a Mentor Commented:
It's not hiding the element because that element doesn't exist in the document yet; the JavaScript is executing before the browser parsed and loaded the HTML into the DOM. Change the last of your code (the if statement) to this:
onload = function() {
    if(g_querystring["type"] == "arth")
    {
        var mydiv=document.getElementById("menu");
        mydiv.style.visibility="hidden";
        mydiv.style.display="none";
        //document.write("Yea worked");
    }
};

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.