Last active
March 6, 2018 19:09
-
-
Save graysonhicks/4fbb5b0d315ceb886417e017ae6a16d9 to your computer and use it in GitHub Desktop.
Getting URL Params in Javascript (Vanilla)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// *** | |
// This is the function that does the work, put it at the top of your JS file (at least above where you are going to use it). | |
// Then you can forget about it. Don't worry about the 'exclude' part. | |
// *** | |
// START COPY AND PASTE | |
(function () { | |
console.log("Gist is running..."); | |
var getUrlParams = function(exclude){ | |
var str = window.location.search; | |
if (str === "" || str === "?" || str === "#") return {}; | |
exclude = exclude ? exclude : []; | |
exclude = exclude instanceof Array ? exclude : []; | |
var p = str.indexOf("?") === 0 ? str.substring(1).split("&") : str.split("&"); | |
var temp, | |
len = p.length, | |
result = {}; | |
for (var i = 0; i < len; i++) { | |
temp = p[i].split("="); | |
if (exclude.indexOf(temp[0]) === -1) { | |
result[temp[0]] = decodeURIComponent(temp[1]); | |
} | |
} | |
return result; | |
} | |
// Example HTML | |
// <input id='my-hidden-input' type='hidden' val='' /> | |
var params = getUrlParams(); | |
console.log("These are the params it captured:"); | |
console.log(params); | |
// params looks like this | |
// { | |
// source: "wcw" | |
// }; | |
// Now this puts source property in to hidden input | |
document.getElementById('my-hidden-input').value = params.source; | |
console.log("Should have worked now..."); | |
console.log("value of the input is: " + document.getElementById('my-hidden-input').value); | |
})(); | |
// END COPY AND PASTE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment