Passing URL Parameters in href Link - javascript

I’m a bit new to this JS stuff and have been surfing and surfing and reading up as much as I can, but I got stumped on this one issue.
I have a website that may contain parameters in the URL. A parameter named “who” to be exact.
If a user comes to the site and their url is http://example.com/?who=123, I want them to be able to click a href link and their parameter get carried on. So if the link goes to http://anotherexample.com, I’d want the link to contain the user’s parameter as well. http://anotherexample.com/?who=123.
What’s the best way to accomplish this? It only needs to be on one of the links, so no concerns about getting the whole site to pass on the parameter.
Thanks!

Would this suffice for you?
Source: https://css-tricks.com/snippets/javascript/get-url-variables/
var svalue=location.search.match(new RegExp("[\?\&]" + "who" + "=([^\&]*)(\&?)","i"));
yourelement.href=yourelement.href+(svalue?svalue[0]:"");

Here is one way you can do it in javascript
first when the document loads write a function in your js to get the parameters from the url
function getparms(variable)
{
let item = window.location.search.substring(1);
let vars = item.split("&");
for (let i=0;i< vars.length;i++) {
let pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
This function would return the following from a url
http://www.somesite.com/index.html?who=100&location=2
Calling getparams('who') would return "100"
So you would call it as:
let myParam = getparams('id');
You can build the url in a new function and navigate to it as:
function goToUrl(urlParam){
let hostAddress= 'yourwebsiteaddress';
let url = "http://" + hostAddress "/?=who" + urlParam;
//go to address
window.location.href = url;
}
which would be called as goToUrl(myParam);
*Disclaimer: I wrote this on the fly so it may not be 100% syntactically correct but it should be accurate enough as pseudo code to help you accomplish what you want.

You talked about href, so I assume all links are set with <a> tag.
There are many options to do that, I'll show you the easiest and cleanest one.
So, assuming the current URL is http://www.example.com/?who=123.
var who = window.location.href.split('?')[1]; // Get `?who=123` from current url
var a = document.getElementsByTagName('a'); // Get all `<a>`
var href;
// Loop through all `<a>`
for (var i = 0; i < a.length; i++){
// Add `?who=123` to all hrefs found.
a[i].href += who;
}
You can freely change document.getElementsByTagName('a') to document.getElementById() to suit your needs.

Related

Change the pathname in the URL of a link while keeping the querystring constant

From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)

Add a class to an object using javascript for specific querystring

I want to use javascript or jquery to add a class to an object based on the URL query string.
So if the url is example.com/?var=1 then I want to add a new class to the object
#mydiv
This would then be repeated for ?var=2, ?var=3 and so on.
Here is what I have tried. The hope for this is that it would add a different class to the object if the query string was either ?var=2 or?var=3
var queryString = window.location.search.substr(1);
switch (queryString) {
case "2": document.getElementById('mydiv').className = 'newclass2';
;
break;
case "3": document.getElementById('mydiv').className = 'newclass2';
;
break;
}
EDIT:
It almost works now....
Here is my current code:
<script>
var queryString = window.location.search.substr(1);
var variant = queryString.split('=')[1];
switch(variant) {
case "stnl2": document.getElementById('getexclusive-sb').className = 'stnlvar2';
;
break;
case "stnl3": document.getElementById('getexclusive-sb').className = 'stnlvar3';
;
break;
}
</script>
It works if the url is "/?v=stnl2"
However Google content adds more to the url such as "?v=stnl2&utm_expid=42387987-0.dmsadhasjkdjasgdjgas-Q.4"
Is there a way for me to ignore the & and all details after so my code still works?
var getUrlVars = function(){
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];
}
if(vars[0] == window.location.href){
vars =[];
}
return vars;
}
var params = getUrlVars();
switch (params['var']){
...
}
Your params will have all the parameters from your query string. just past the variable name as a string and you will get the value of that parameter.
The solution you tried has two issues.
First, you are getting the number of variant incorrectly. With your code, queryString will be like "var=2". So if you want only number, you should also split it by =:
var queryString = window.location.search.substr(1);
var variant = queryString.split('=')[1];
switch(variant) {
// ...
}
Note that this still actually doesn't check the name of your parameter, i.e. var=. If it is the only parameter, it would work. Otherwise, for proper handling of query string in JS you might want to look at this question
Second, look attentively into your switch. Both branches are actually identical, so they would do exactly the same regardless of queryString. Seems like you copy-pasted it unintentionally.
UPD:
As a said in my original answer, I just pointed you to some issues in your solution and how to fix them. It would not work if there is more than one parameter. Of course, you can just ignore all the string after &. But still there would be many cases in which it still won't work: what if your parameter is not the first?
I think it is not a good idea to make such assumptions, so we come to what I said previously: you might need proper, full-fledged parsing of parameters. The link that I mentioned provides A LOT of solutions for this particular task, you may choose any of them. Another option is to use some existing library which have such function provided. That question and some other SO questions pointed me to these two:
jquery.parsequery — a jQuery plugin for this only purpose, with which you can do variant = $.query(location).get("paramName"). Seems to be old and not updated.
jsurl — a library for making different things with URLs, in particular, you can do variant = (new Url).query.paramName with it.
NB: (replace paramName with your actual parameter name, v or var or whatever)
Of course there could be some other good libs for it, also try googling on your own.

How to find a ModalPopupExtender in a JavaScript?

I need to write a Javascript function that run from Master page, to find a ModalPopup in the contenct page and close it. Following code works, but not what I want. I need use something like mpeEditUser.ClientID, but I got an error. Also, it would be nice if I could find a ModalPopup without knowing its id, by its type (ModalPopupExtender) instead. Any suggestion?
function CloseModalPopup() {
var mpu = $find('ctl00_ContentPlaceHolder1_mpeEditUser');
mpu.hide();
}
Here is my solution: (If you see any problem, please let me know. Thanks)
I get the ModalPopup id in the codebehind, and pass it to my javascript function.
In the Page_Load of the default.master.cs:
ContentPlaceHolder cph = (ContentPlaceHolder)FindControl("ContentPlaceHolder1");
string sMpeID = (AjaxControlToolkit.ModalPopupExtender)cph.FindControl("mpeEditUser");
In my Javascript function:
var mpe = $find('<%=sMpeID%>');
if (mpe != null) {
mpe.hide();
}
Its likely the tag is getting mucked up by being called through another page, this happened to me. I don't know the best fix for you, however the way I addressed the issue was to first find the mpe through a javascript function that looked for a vague match out of all of the elements on the page.
var elemets = document.getElementsByTagName("*");
var mpe;
for (var i = 0; i < elemets.length; i++) {
var id = elemets[i].id
if (id.indexOf("mpe") >= 0) {
mpe = elemets[i];
}
}
If you have more then one mpe on the page you may want to match more if the string. For me the elements function only returned about 50 elements, so it was not too much overhead. That may not be the case for you, but even if you dont use this function in the final product it will assist you in discovering the actual ID of the elment.

Add body #id based on url

Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.
- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...
My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?
- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2
Here's the JS code I'm using (found online)
$(document).ready(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".html","");
if(truePath === "") {
$("body").attr("id","index");
}
else {
$("body").attr("id",truePath);
}
});
Thanks in advance!
edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.
http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.
Using the javascript split function might be of help here. For example (untested, but the general idea):
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
$('body').id = segments[0];
Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
for (var i = 0; i < segments.length; i++) {
$('body').addClass(segments[i]);
}
EDIT:
Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...
var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');
If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...
url = url.replace(/\?.+$/,'');
Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..
var $body = $('body');
for ( ... ) {
$body.addClass( ...
}
Your regex is only going to select the last part of the url.
var getLast = pathname.match(/./(.)$/)[1];
You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.
If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.
edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.
What are you actually trying to do?
Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.
$(document).ready(function() {
$("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}
You want to get the first part of the path instead of the last:
var getFirst = pathname.match(/^\/([^\/]*)/)[1];
If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:
var getLast = pathname.match(/\/(page\d+)\//)[1];
The above would match "page" followed by a number of digits (omitting the 'html' ending too).

function to define current class in js

What I want to do is to have a function that executes to define a "current" class to an <li> tag, depending on the page name. For example, if the page is named index.php, I want the function to determine if the link within the <li> tag is the same name as the page (index.php). I'm sorry I'm not the best at explaining this. Here's an example code.
<ul id="navigation"><li><a href="index.php"></li></ul>.
I want the class "current" defined into the <li> tag if the link is the same as the page name. Is there any way to do this? Or am I on a futile mission?
I think what you are asking is you want to change the look of links that are pointing to the present page. Here is what the code would look like.
var list=document.getElementsByTagName('a');
var page=window.location.pathname;
var i=list.length;
while(i--){
if(list[i].src.indexOf(page)>0){
list[i].className='current';
}
}
Note this is not a very accurate method. The basic structure is correct, but for example a link somewebsite.com is actually pointing to somewebsite.com/index.php. So depending on the link this could cause a problem on the home page. Also, depending on how your links are setup you are probably going to have to the parse the page variable. It will return something like. /help/faq/foo.php while the page may only have a link to faq/foo.php. This all depends a lot on the setup of your site so I will leave it for you to tweak.
You added more details since I posted so I thought I would note that you would only need to make a list of the links in the <li> tags not all the <a> tags in the page.
Well...okay...
function liClass(context) {
//Choose your parent node
context = context || document;
var pathparts = window.location.pathname.split('/'); //split on path
var curfile = pathparts[pathparts.length-1]; //last item is the filename right?
var lis = context.getElementsByTagName('li');
for (var i=0, l=lis.length; i<l; i++) {
var a = lis[i].getElementsByTagName('a');
if (!a.length) continue; //li has no a, moving on...
//Okay, this match might need some work, tried
//to make it fairly forgiving, tweak for your needs
if (a[0].href.indexOf(curfile) != -1) lis[i].className = 'current';
}
}
Feel free to try it out, let me know if it works or not, cause I did not test it...
Compare the href's of the location object, and the anchor DOM element. If they match, then that is the current class.
If the current page is http://www.example.com/home which contains a relative link,
Questions
Then the href property of the DOM object will contain the absolute path, and not just the relative part.
link.href = "http://www.example.com/questions"
A function that loops through each link could then be written as,
function markCurrent(list) {
var listItems = list.getElementsByTagName("li");
for(var i = 0; i < items.length; i++) {
var link = listItems[i].getElementsByTagName("a")[0];
if(link && (link.href == location.href)) {
listItems[i].className += ' current';
}
}
}
Pass the root <ul> node to the function.
markCurrent(document.getElementById("navigation"));

Categories