Javascript/html keep url params - javascript

say I provide someone with a link to my page that looks like the following
www.linkone.com?something=ten
When they visit the page, the param will be visible within the url for that page. If on that page I then have a link like so
Link Two
When they click on it, Link Two's url will look like
www.linkone.com/linktwo.html
Is there any way to add the param from the first link onto any other links within the page? So when they visit Link Two, I want to url to end up being
www.linkone.com/linktwo.html?something=ten
I know it is probably possible via javascript, but the homepage has a lot of links on it to other pages within the site, and I need to param on all links. What is the best way to achieve this?
Thanks

$('a:not([href=#])').on('click', function (e) {
e.preventDefault();
location.href = this.href + "your param";
});

My suggestion is:
$('a:not([href=#])').click(function(e) {
e.preventDefault();
// Getting query-string parameters from current page URL.
var query = location.search.substr(1);
// Getting URL from current link;
var url = new URL($(this).attr('href'));
// Updating query-string parameters of current link.
url.search += (url.search.indexOf('?') == 0 ? '&' : '?') + query;
// Getting the link target.
var target = $(this).attr('target');
// Navigating to new URL.
if (target) {
window.open(url.toString(), target);
} else {
location.assign(url.toString());
}
});

One way to achieve a similar function is to use cookies or session. When a user visits your site with additional param, set a cookie on the parent page with that param so that it would be available for other calls/links. You could do that in session as well. session would retain the value till the session times out and cookie expires based on the expiry date set for it.
Link to Cookie Reference

You can update anchors href attributes at Document Ready. Below code solution for current HTML querystrings carries over the selected anchors href attributes.
var selectedAnchors = $("a");
selectedAnchors.each( function () {
var itemHref = $(this).attr("href");
if ( itemHref.indexOf("?") > -1 )
itemHref += "&";
else
itemHref += "?";
itemHref += location.search.substr(1);
$(this).attr("href", itemHref );
});

Please try this. Just replace word "something" with your own parameter.
Thanks
$("a").click(function(e){
e.preventDefault();
var a = $(this).attr('href');
var something = getUrlParameter('something');
var newURL = a+"?something="+something;
window.location.href = newURL;
});
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(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 sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
HTML:
Google

This is possible (with php):
<a href="http://www.linkone.com/linktwo.html?something=
<?php echo $_GET["something"]; ?>"> Link Two </a>

Related

Linking Directly To An Open Modal Window Through a URL?

I don't know much at all about coding so hopefully i worded the question correctly.
What I am trying to do is link a person to a specific modal window on another website. In this example, I will use the Menards weekly ad to show what I would like to do.
I would like to link somebody directly to the weekly flyer page with the modal window already open for a specific product such as the $74.99 5 Shelf Unit, which when selected opens this window (http://i.imgur.com/lntNUpK.png). This is the window that I would like to directly link to somebody.
Is there a way to modify the URL to make this possible? About all I know how to do is how to link to a specific page of the URL which would look like this /main/flyer.html?page=5
One other thing to mention is if you go to the website that provides the ads, Flipp, it does allow you to directly link to the window https://flipp.com/item/175356457-muscle-rack-5shelf-steel-unit
Thanks for any help!
Yes it is possible with some javascript, it will look for #myModal on the url if it finds it, it will load the modal:
just put this at the end of your page:
$(document).ready(function() {
if(window.location.href.indexOf('#myModal') != -1) {
$('#myModal').modal('show');
}
});
Now just use the following url:
http://www.mywebsite.com/page.html#myModal
*your modal must have an id:
<div class="modal" id="myModal">
How about that?
function openModalOnHash() {
if(window.location.hash) {
var hash = window.location.hash.substring(1);
$('#'+hash).modal('show');
}
}
$(document).ready(function() {
openModalOnHash()
});
I believe this should work. Only opens modal (if modal exist) with specified ID in URL
$(document).ready(() => {
const href = window.location.href
const modalID = href.split('/').reverse()[0]
if(modalID){
$(modalID).modal('show')
}
})
Yes, you can catch get param on url , https://www.exampleurl.com/?param=ModalIdShow
// Start Page
$(function(){
var param = GetURLParameter('param');
if(param == 'ModalIdShow'){
$("#ModalIdShow").modal("show");
}
});
//Catch param
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}

Toggle between functions - only execute either one on pageload

I want to toggle between two jQuery functions. It has to be done on page load - and each page load should only execute one of the scripts.
This is what I got so far:
HTML:
<button class=".click">Click me</button>
Script:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
});
});
This Gets me a bit on the way, the first click adds ?param=1 on the first click - nothing happens - second click it adds the ?param=addClass and the body gets the class. If I click again it adds ?param=addClass every time.
I want one of the script to run as default - then I want the first button click to reload and run the other script instead. If I click once more I want it to reverse the url so the first script loads, like a toggle.
I now there is an easy way to just toggle classes, but I specifically need to run one of two scripts on a new page load.
Update:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
});
This set the body class on first page load - then first click ads ?param=1 but doesnt change the body class. Second click replaces ?param=1 with ?param=addClass and changes the body class - after that the toggles works. So How do I make it work from the first click?
This will be the default functionality, if no query string is present then add ?param=1:
var url = window.location.href;
if(url.indexOf('?param=1')==-1 )
{
window.location.href = url+"?param=1";
}
This will be the onclick functionality to toggle the urls as it is replacing the existing functionality.
$('.click').on('click', function() {
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
If you want to toggle the classes as well you can use .toggleClass("test secondtest")
The issue you have is in this if:
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
Scenario 1: /test.html
indexOf('?') will be negative. You will then redirect the user to /test.html?param=1
Scenario 2: /test.html?param=1
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=1?param=addClass
Scenario 3: /test.html?param=addClass
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=addClass?param=addClass
So... what is wrong?
You are using window.location.href. Excellent for setting the path but bad if you want to actually manage the query parameters.
Solution
var url = window.location.pathname;
var hasParams = window.location.href.indexOf('?') > -1;
if (hasParams) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
Since you are redirecting on the same host (seen with your code), you only need the pathname. pathname doesn't include parameters (?key=value&...) and can be used to redirect a user on the same domain.

window.location.assign(varString) wont work

I have java script function to check the URL and split it,
I ask a question and depends on the answer it will forward the user page
all works fine until I use window.location.assign();
with string inside (=window.location.assign(path);) instead of fixed URL (=window.location.assign("http://stackoverflow.com");)
what can i do?
thanks...
var register=...;
var login=...;
function link(type) {
var urlPath = document.URL.split("/");
if (type == "register") {
var path= urlPath[2] + register;
window.location.assign(path);
}
else {
var path = urlPath[2] + login;
window.location.assign(path);
}
event.preventDefault();
}
You should use the full URL.
window.location.assign(urlPath[0]+'/'+urlPath[1]+'/'+urlPath[2]+register);
window.location.assign(urlPath[0]+'/'+urlPath[1]+'/'+urlPath[2]+path);
Or
window.location.assign(window.location.origin+register);
window.location.assign(window.location.origin+path);

script to redirect if the url contains a querystring

SHORT: Need a script to remove the parameters on URL IF EXIST. Must be jquery/Script/
LONG: I have a site where I send traffic to with lots of parameters. These are processed instantly with php to cookies. After my cookie set I would like to refresh the same page but WITHOUT parameters. I cannot do it php since the cookies need to be processed by an iframe so I need a jquery/script to do it AFTER cookies are set via the iframe.
Thanks guys! :)
The below code will remove the query string parameter and will reload the page
window.location.href = window.location.protocol+"//"+window.location.hostname+window.location.pathname
The search attribute of window location describes the GET parameters on the url so -
if (window.location.search != "") {
window.location.search = "";
}
You may want to check out this question for a another solution.
And have a look at the MDN Documentation on window.location for more info.
I think you need to use something like:
var url_update= false;
var stripped_url;
function removeparametersFromURL(url_string) {
if (url_string.indexOf("#") > 1) {
URL = url_string.split("#")[0];
url_update= true;
}
if (url_string.indexOf("?") > 1) {
URL = url_string.split("?")[0];
url_update= true;
}
return URL;
}
var stripped_url = removeparametersFromURL(top.location.href);
if(url_update){
top.location.href = stripped_url;
}
setTimeout(function(){
stripped_url = removeparametersFromURL(top.location.href);
if(url_update){
top.location.href = stripped_url;
}
},5000); //will call function after 5 seconds

JS: incrementing pages (page1.html, page2.html,page3.html...) for window.replace

What approach should for this scenario. I want the page to go to the next page after it finishes all the function it needs to.
so, example. after all function for page1.html has been done, it will call a function next_page().
next_page() function will evaluate the current page and add "1" it. so from page2.html it will now be page3.html. page3.html will also contain the same function of the previous html, that after all the functions have been done, it will call the next_page() function that will also evaluate the current and increment it.
//current_url = "mysite.com/page1.html"
var current_url = window.location;
var end_page = "mysite.com/page12.html"
var increment_url = eval(current_ur + 1 );
if(current_url != end_page ) {
setTimeout(next_page,2000)
}
else {
alert("this is the last page!")
}
function next_page() {
window.location.replace(increment_url);
}
var increment_url = addone('mysite.com/page1.html');
returns mysite.com/page2.htm
function addone(url) {
var pattern=new RegExp("(.*)([0-9+])(\..*)");
var match=pattern.exec(url);
return match[1] + (parseInt(match[2]) + 1 ) + match[3];
}
​
so assuming the example URL you gave is accurate enough that the regular expression will work use
var increment_url = addone(current_url);
The easiest thing to do would be to have a hidden input on each page that has the value of the next page url. This would allow you to use arbitrary page urls and still be able to get the effect you want.
Using jQuery
$(function() {
setTimeout(function() {
var url = $('#next_page_url').val();
window.location.replace(url);
}, 2000);
});
<input type="hidden" id="next_page_url" value="http://mysite.com/page2.html" />

Categories