Show <div> when a specific URL Parameter is met - javascript

I have a form in Google Sheets, which passes URL parameters to a page, which then should show content based on the URL parameters.
So if a person checks "item 1" and "item 2" in the Google Sheet, the parameter gets passed on as follows:
https://my-url.com/?item1=value1&item2=value2
Now there's several div containers, which are set to display:none with css. When the URL parameter is met, the hidden div container should show up. So the html is:
<div class="hidden" id="value1">This content should show, when the URL parameter value 1 is passed</div>
<div class="hidden" id="value2">This content should show, when the URL parameter value 2 is passed</div>
I've found some code online, which does pretty much that, but it can only display one div at a time: https://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/
My problem is, that for every passed parameter, a field has to show.
Can anyone help me with this? I'm really not an expert in js by any means.

Good Luck
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var item1 = getParameterByName('item1');
var item2 = getParameterByName('item2');
if (item1 == "value1")
{
document.getElementById("value1").style.display = "block";
}
if (item2 == "value2")
{
document.getElementById("value2").style.display = "block";
}
.hidden
{
display: none;
}
<div class="hidden" id="value1">This content should show, when the URL parameter value 1 is passed</div>
<div class="hidden" id="value2">This content should show, when the URL parameter value 2 is passed</div>

You could do something like this:
$.each(getUrlVars(), function(i, x) {
$('#' + x).show();
})
function getUrlVars() {
var vars = {},
hash;
var hashes = url.slice(url.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;
}
getUrlVars is taken from this answer, and modified a bit.
Demo
var url = "https://my-url.com/?item1=value1&item2=value2"; //replace with window.location.href
$.each(getUrlVars(), function(i, x) {
$('#' + x).show();
})
function getUrlVars() {
var vars = {},
hash;
var hashes = url.slice(url.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;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hidden" id="value1">This content should show, when the URL parameter value 1 is passed</div>
<div class="hidden" id="value2">This content should show, when the URL parameter value 2 is passed</div>

try this
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
let item1 = getUrlParameter('item1');
let item2 = getUrlParameter('item2');
if(item1 =='value1' &&item2 =='value2')
{
document.getElementById('showhide').style.display = 'block';
}
<div id="showhide" style="display: none">
hi hi
</div>

Related

URL parameters are reordered when using anchor links with Inheriting UTMS

I am using a javascript on my site, which always inherits the UTM parameters to the links on the site.
However, this is not working, when the links are anchor links to a section of the site and the link the visitor used to visit the page contains the "gclid" parameter from google.
For example:
A visitor uses this link to visit a site:
domain.com?utm_source=test&utm_medium=test&utm_campaign=test&gclid=12345
The button link on the site with the anchor link will look like the following:
domain.com&gclid=12345?utm_source=test&utm_medium=test&utm_campaign=test#anchor
For some reason the "&gclid" part changes its position.
I've tested it with a link without an anchor and in this case the "gclid" parameter doesn't get inherited and the link works.
Of course, the second domain isn't working anymore and leads to a 404 error.
Does someone have an idea what could be the cause for this?
This is the javascript I am using to inherit the UTMs:
(function() {
var utmInheritingDomain = "grundl-institut.de"
utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
links = document.getElementsByTagName("a"),
utms = [
"utm_medium={{URL - utm_medium}}",
"utm_source={{URL - utm_source}}",
"utm_campaign={{URL - utm_campaign}}"
];
for (var index = 0; index < links.length; index += 1) {
var tempLink = links[index].href,
tempParts;
if (tempLink.indexOf(utmInheritingDomain) > 0) {
tempLink = tempLink.replace(utmRegExp, "");
tempParts = tempLink.split("#");
if (tempParts[0].indexOf("?") < 0) {
tempParts[0] += "?" + utms.join("&");
} else {
tempParts[0] += "&" + utms.join("&");
}
tempLink = tempParts.join("#");
}
links[index].href = tempLink;
}
}());
EDIT: It seems like the following script don`t causes this problem:
<script>
(function() {
var domainsToDecorate = [
'domain.com',
],
queryParams = [
'utm_medium',
'utm_source',
'utm_campaign',
]
var links = document.querySelectorAll('a');
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) {
if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
links[linkIndex].href = decorateUrl(links[linkIndex].href);
}
}
}
function decorateUrl(urlToDecorate) {
urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
var collectedQueryParams = [];
for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
if (getQueryParam(queryParams[queryIndex])) {
collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
}
}
return urlToDecorate + collectedQueryParams.join('&');
}
// borrowed from https://stackoverflow.com/questions/831030/
// a function that retrieves the value of a query parameter
function getQueryParam(name) {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
return decodeURIComponent(name[1]);
}
})();
</script>
You really should not change URLs with regexp and string manipulation.
Here is the recommended way
const url = new URL(location.href); // change to tempLink
utms = [
"utm_medium=med",
"utm_source=src",
"utm_campaign=camp"
];
utms.forEach(utm => url.searchParams.set(...utm.split("=")))
console.log(url.toString())

Overwrite UTM Parameter

We do have some Campaigns (Google, facebook,...) When the user arrives the landingpage (abo.mysite.com) he does have the utm parameter utm_source=theCampaignSource. When the user clicks an CTA the CTA gives an new UTM utm_source=abo and he goes to shop.mysite.com.
We are not able to remove the UTM from abo.mysite.com.
Is there a way to check if a user have already an UTM, and when he does have one to kepp them until shop.mysite.com? So we know that the user is comming from Google (...)?
We know that how this Thing is set up is a very bad practice, and we are working on it.
Ive found a code snippet which is manipulating the links on a site:
links.forEach(function(link){
link.setAttribute("href","abo.mysite.com")
})
but i couldn get it work - cause i do have a lack of experience.
Update
To my specific needs a made it that way:
1) Remove existing UTM from Links on the Site
<script>
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
2) Hash the UTM in the URL
<script>
if(!window.jQuery) {
document.write('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">\x3C/script>');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
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;
}
var parameters = getUrlVars();
var utm_source = decodeURIComponent(parameters['utm_source']);
var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
var utm_medium = decodeURIComponent(parameters['utm_medium']);
</script>
3)rewrite every URL on the Site with the hashed UTMs
<script>
$('a').each(function(){
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
});
});
Edit
Thanks to Michele Pisani
this works well - BUT, if a user does not have an UTM, and he clicks the button, the UTM will be set to undefined
Is there a way to set the UTM Parameter from the URL when the User already has one, or to use the existing UTM (which are hardcoded in the button) when he does not have an UTM in the URL.
Edit 2 & update
Finally - with the help of you guys - i found a solution:
<script>
var link = document.querySelectorAll('a:not([href*="#"])');
for (var i = 0; i < link.length; i++) {
//link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
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;
}
//var parameters = getUrlVars();
//var utm_source = decodeURIComponent(parameters['utm_source']);
//var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
//var utm_medium = decodeURIComponent(parameters['utm_medium']);
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
//var c = url.searchParams.get("c");
var utm_source = url.searchParams.get("utm_source");
var utm_campaign = url.searchParams.get("utm_campaign");
var utm_medium = url.searchParams.get("utm_medium");
$('a:not([href^="#"])').each(function() {
if(utm_source != "" && utm_source != null){
var href = $(this).attr("href");
href = href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
$(this).attr("href",href);
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign=' + utm_campaign + '&utm_medium=' + utm_medium);
}
});
});
</script>
With JavaScript, to remove UTM parameters from links in page you can try this function with regex:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
If you are using Google Tag Manager you can add it in a custom HTML tag and fires it on DOM Ready.
If you want to keep the fragment in the URL you can modify the function in this way:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
arr_link = (link[i].href).split("#");
var fragment = "";
if (arr_link[1]) { fragment = "#" + arr_link[1]; }
var my_new_url = arr_link[0].replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
link[i].href = my_new_url + fragment;
}
const ourUTMs = new URL(location.href).searchParams;
document.body.onclick = (e) => {
if (!isParamsContainsUTM(ourUTMs) || e.target.tagName !== "A") {
return;
}
try {
// Is valid url?, else we go to catch =)
const url = new URL(e.target.href);
e.preventDefault();
// Remove all utm params from link;
Array.from(url.searchParams).forEach(([k]) => {
if (k.startsWith("utm_")) {
url.searchParams.delete(k);
}
});
// Add our utm_ params to link
Array.from(ourUTMs).forEach(([k, v]) => {
url.searchParams.append(k, v);
});
// Open URL
window.open(url.toString());
} catch (e) {}
};
const isParamsContainsUTM = (arr = new URLSearchParams()) =>
Array.from(arr).some(([key]) => key.startsWith("utm_"));

Remove match word using jQuery

I want to split and join two type of url. For example
Url 1 :
http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC
Url 2 :
http://localhost/site/index.php?route=product/category&path=20&limit=8
<input type="hidden" class="sort" value="http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC" />
<input type="hidden" class="limit" value="http://localhost/site/index.php?route=product/category&path=20&limit=8" />
I'd like to join the query strings but remove duplicates.
I'm looking for this result at last
http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC&limit=8
var getUrlParameter = function getUrlParameter(sParam, url) {
var sPageURL = decodeURIComponent(url),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
Now read individual parametrs by
var order = getUrlParameter('order', 'http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC');
var limit = getUrlParameter('limit', 'http://localhost/site/index.php?route=product/category&path=20&limit=8');
and make a new url by using the parameters.
You could go with getting the query parameters in an array and de-duplicating them.
var url1 = "http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC";
var url2 = "http://localhost/site/index.php?route=product/category&path=20&limit=8";
var url = (url1.split`?`[1]+"&"+url2.split`?`[1]);
var result = url1.split`?`[0]+"?"+Array.from(new Set(url.split`&`)).join`&`;
console.log(result)
Note that you're left with order=ASC and order=DESC, of which only the last is processed. But looks like that's what you want...
For older browsers:
var url1 = "http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC";
var url2 = "http://localhost/site/index.php?route=product/category&path=20&limit=8";
var url = (url1.split('?')[1]+"&"+url2.split('?')[1]);
var result = url1.split('?')[0]+"?"+url.split('&').filter(function(x,i){
return url.split('&').indexOf(x) == i;
}).join('&');
console.log(result)

compare a select option value and a value from URL

I have a select tag to choose categories, each option contain the category number as value.
The category number is in the URL string.
I'm trying to write a JS to check if the option value is the same as the category number in the URL and if so make the option selected. so far the script dosnot work.
What am I doing wrong?
here is the code:
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] === VarSearch){
return KeyValuePair[1];
}
}
}
function compareValue(){
var x = document.getElementById("selectcategory").length;
for (var i = 0; i < x; i++){
var categNo = document.getElementById("selectcategory").options[i];
var UrlValue1 = GetUrlValue('icid');
if (categNo === UrlValue) {
document.getElementById("selectcategory").options[i].selected = true;
}
alert(UrlValue1);
}
}
if needed, I will send a link to the work.
if doing that with jquery is easier, i will be happey to learn.
thanx.
The problem is that categNo should be the value of the corresponding option tag. Also it's better to cache select element and not requery DOM in the loop:
function compareValue() {
var select = document.getElementById("selectcategory");
var x = select.options.length;
for (var i = 0; i < x; i++) {
var categNo = document.getElementById("selectcategory").options[i].value;
var UrlValue = GetUrlValue('icid');
if (categNo === UrlValue) {
select.options[i].selected = true;
}
}
}
Demo: http://jsfiddle.net/dj7c6sdL/

javascript for changing link's href in html page

My problem is the following:
I have a page with many links
Some of them have a specific pattern :
http://www.example.com/.../?parameter1=...&parameter2=PARAMETER2
What i want to do is to change these links' href to the value of the parameter2 using JavaScript.
For example if i have a link like :
text here
what i want to do after the script runs is to have a link like this:
text here
Any suggestion would be truly appreciated!!!
Thank you all in advance!!!
If you are using jquery
then use the following code
$(function() {
$("a[href^='www.example.com']").each(function(){
var ele = $(this);
var href = ele.attr("href");console.log(href);
var index = href.lastIndexOf("parameter2");
var param_2 = href.substring((index + 11));
ele.attr("href", param_2);
});
});
http://jsfiddle.net/LVNeC/
function getUrlVars(_url)
{
var vars = [], hash;
var hashes = _url.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;
}
var myLINK = document.getElementById("mylink");
var url = myLINK.href;
myLINK.href = getUrlVars(url )["parameter2"];​

Categories

Resources