Tuesday 18 October 2016

javascript - jquery get querystring from URL











I have the following URL:



http://www.mysite.co.uk/?location=mylocation1



What I need is to get the value of location from the URL into a variable and then use it in a jQuery code:



var thequerystring = "getthequerystringhere"

$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);


Does anyone know how to grab that value using JavaScript or jQuery?


Answer



From: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html




This is what you need :)



The following code will return a JavaScript Object containing the URL parameters:



// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}



For example, if you have the URL:



http://www.example.com/?me=myValue&name2=SomeOtherValue


This code will return:



{
"me" : "myValue",
"name2" : "SomeOtherValue"

}


and you can do:



var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...