How to keep query string parameters as user navigates through the website - javascript

I have a situation where I want to preserve a query string between clicks on my Wordpress website.
E.g.
www.mywebsite.com/?utm_source=mysource
When navigating from this link to another page of the website that query string should persist.
E.g.
www.mywebsite.com/anotherpage/?utm_source=mysource
So I decided one easy way to do this would be to modify the javascript so that my function is fired when a click on an anchor tag occurs.
//Ensures that the query string persists between clicks on the site
$("a").on("click", function (event) {
event.preventDefault();
window.location.href = event.currentTarget.href + window.location.search;
});
However this doesn't work for other elements on the page like buttons which are not anchor tags but still contain hrefs that modifiy the window location when they are clicked. For example in the php scripts of the theme there is code such as:
<button onClick="location.href=www.anotherwebsite.com"</button>
I could implement another function that implements the same behavior for button elements but I am concerned that whenever another element is added I will have to check for a new type. Is there a better way to ensure that whenever the window location is changed my query string persists?
FYI: I am not allowed to put the information in a cookie which is another way I thought of keeping track of the parameters.

several suggestions
client side
In using jquery, it might be easier to just find clickable elements, or have the WordPress theme add css classes, if useful ones aren't there already.
server side
In WordPress, use sessions (but see below), and a rewrite or redirect rule using add_query_arg().
Note about sessions and WordPress: You can't rely on PHP sessions; instead use the database, perhaps via an existing plugin like WP Session Manager or WordPress Native PHP Sessions.

Try this to append query paramters in all anchor tags:-
$('a').each(function() {
var href = $(this).attr('href');
var querystring =
window.location.href.slice(window.location.href.indexOf('?') + 1);
if(href && querystring){
if(querystring.indexOf('=') >= 0)
{
$(this).attr('href', href+'?'+querystring);
}
}
});

Related

jQuery / JavaScript Hide an element based on current page?

lets say im on this page
http://MyWebSite.com/users
and there is a link button on this page lets say
<span class="user">
go to page
</span>
If i click on the link it goes to for example
http://MyWebSite.com/users/jake
So now when im on this page there is same button exists and i want to hide it using javascript or jQuery :)
More info: The {$record->url()} in the link is dynamic goes to a page depending on the user, so i must use {$record->url()} in the script to match the current page link
Is this possible?
(I'm on a phone so this is the best I can do for now)
Maybe something like....
if (window.location.href.replace(location.hash,'') == "http://kodeweave.sourceforge.net/editor/") {
$(".nicole").hide()
} else {
$(".michael").hide()
}
You could use jQuery's equals selector to hide any elements that had an href attribute that pointed to your target page using the following code :
// This assumes that the URL will be populated via your server-side code in
// { ... } braces
$('[href="{$record->url()}"]').hide();
likewise, if you just wanted to hide any elements that pointed to the current URL, you could do the same thing via a bit of string concatenation :
// This would hide any elements that point to the current URL
$('[href="' + window.location.href + '"]').hide();
If you can avoid it though, you may want to consider hiding this using server-side code (i.e. using a conditional to determine when certain elements should / should not be rendered).

How can I insert links into HTML using javascript without the limitations of document.getElementById

First, let me explain what I am trying to accomplish. I currently have 8 small websites that are identical except for a header image and the href links.
I am looking for a way to minimize maintenance and potential for human error each time these pages need updating.
For example, say I have 2 links that point to State specific login pages.
Student Login
Teacher Login
In the past, I have been making copies of the updated HTML, then search and replace "stateId=WA" for "stateId=MI"
I started to see if I could make the URL using javascript and just append the 2 digit State ID using some function. That way I would only have to update the code, then copy it and replace the 2 digit state ID in one place, in one file.
I made progress by using the following external javascript file
function getParam() {
return 'WA';
}
function getLink() {
document.getElementById('studentLogin').href = 'https://www.mypage.com/studentLogin?stateId=' + getParam();
}
function getLink() {
document.getElementById('teacherLogin').href = 'https://www.mypage.com/teacherLogin?stateId=' + getParam();
and then using this in the HTML
CLICK ME
This worked, until I figured out that I can't have more than one element in the HTML with the same id. For example, one of the pages has a link to the Student Login in the Menu, and also has a link to the same place in the main content of the HTML, and only one of them would work.
So I suppose I could create several functions in the external javascript file each with their own ID, then update the HTML to call the new IDs, but I am in search of a better way.
All I really care about is minimizing maintenance, since I currently have 8 of these landing pages, but we could have more in the near future. Since there are only 4 distinct links off of these pages, it would be fine if I could figure out how to store the entire link in a variable, and just call that variable in the
<a> tag
Thank you for your help.
You can add classes to the relevant links, and then get the elements with document.getElementsByClassName("myclass")
test1test2
And in JS:
var links = document.getElementsByClassName("myclass")
This would make links an array containing all the links over which you could iterate to apply your modifications.
Sounds like a job for a progressive enhancement.
I would suggest you add a attribute the html link; data-state-change. Then any future links you write you just add the attribute.
//keep the base url in the tag
<a href="https://www.mypage.com/studentLogin" data-has-state>Click Me<a>
//now using jquery attach to all links that have that data- element.
$('body').on('click', '[data-has-state]', function(e){
// eat the click
e.preventDefault();
//get the url
var url = $(this).attr('href') + '?stateId=' + getParam();
window.location = url;
);
You could do something similar with a css class also instead of an html data- attribute. Then it would be.
$('body').on('click', '.someCssClass', function(e){
// eat the click
e.preventDefault();
//get the url
var url = $(this).attr('href') + '?stateId=' + getParam();
window.location = url;
);

jquery - significance of .hash in this function

I borrowed someone's jquery function and adapted it for my own use, but I do not understand exactly how it works. Specifically the line var content = this.hash.replace('/', '');
Could someone please explain .hash in this context?
The full jsFiddle is here: http://jsfiddle.net/bsapaka/KjcnL/3/
$(document).ready(function () {
var tabs = $(".tabs-group li a");
tabs.click(function () {
var content = this.hash.replace('/', '');
tabs.removeClass("active");
$(this).addClass("active");
$("#panel > div").hide();
$(content).fadeIn(700);
$(this).delay( 800 );
});
});
That gets the part of the href after (and including) the #.
An <a> element has several such properties, like:
hash
host
href
hostname
pathname
protocol
search
In that context, they're using the hash as an id to fetch another element. Because the # is present, it's a valid id selector.
If you look at the way the following anchor tag is set up:
<li>Health & Fitness
The hash value is the part of the href attribute after and including the hashtag: #
In this case, the code stores the ID of the element to be shown when the anchor tag is clicked in the hash, then a few lines below, the value of the hash is used as a JQuery selector to show the specified element (note that the hashtag is also the ID selector in JQuery):
var content = this.hash.replace('/', ''); // returns '#hnf' for the <a> tag above
[...]
$(content).fadeIn(700); // '#hnf' is the ID of an image on your page to display
Beware though, because using hash navigation in this way may cause unexpected results when a user tries to use the back button. Hashtag navigation is usually used to create entries in a browser's history upon displaying new data without actually navigating to a different HTML page. You should research hash navigation further for ways to prevent some of the pitfalls. The following SO post may be a good place to start if you find the back button behavior is undesired:
How to make the browser back button disregard hash tags?
I believe that hash is found on elements that contain an href attribute or property
the bolded text is the hash.
http://www.example.com/page.html#stuff

script to replace href http:// with //

The e-commerce platform I use, bigcommerce, uses global variables to insert data dynamically. I don't have access to the php needed to manipulate the variables server side.
Unless at checkout, the variables all render http: links, I'd like a script to make them relative so if someone wants to browse via https: all of the menu and category links will comply.
I'm currently use this to correct my main nav but it is obviously not a best case solution, and the remainder of the generated links remain http
<script type="text/javascript">
relativeLinking();
function relativeLinking(){
var GLOBAL_PagePath = "%%GLOBAL_PageLink%%".substring(5);
document.getElementById("%%GLOBAL_PageName%%").setAttribute("href", GLOBAL_PagePath);
};
</script>
you can tranform all links using this code:
$(function() {
$('a').each(function() {
var self = $(this);
self.attr('href', self.attr('href').replace(/.*\/\//,'//'));
});
});
Dustin,
This Javascript code
var GLOBAL_PagePath = "%%GLOBAL_PageLink%%".substring(5);
document.getElementById("%%GLOBAL_PageName%%").setAttribute("href", GLOBAL_PagePath);
sets the attributes. Why require this and not just deliver the correct HTML in the first place.
One assumes that needing this that the web master does not know (or care?) the HTML/PHP/JS etc on the two sites (http:// and https:// protocol).
Certain files should be on one site and nor the other. Vice - Versa.

Change href on unload (or location.href change)

There are several links (and pieces of Javascript) throughout our site that contain /2012/responses/{pathParams...} and I now need to conditionally add to the path, if it's a webview.
if (isWebview) {
// use '/2012/responses/webview/{pathParams...}'
} else {
// use '/2012/responses/{pathParams...}'
}
I can handle the links by inspecting document.links, but I'm wondering if there's a way to handle pieces of Javascript that use window.location = '/2012/responses/...'. One method is to create a function that does the window.location change and replace the window.location statements with the function. But, is there a way to handle it as an event, so when the page is changing I could conditionally insert the /webview in the URL? Browser restrictions seem to limit the beforeunload event to only prompting the user.
I think you can't. I have 2 options for you:
Option 1:
Do a replace all to your code using ternary inline if --> i recommend that
sample:
search for:
'/2012/responses/{pathParams...}'
replace with:
'/2012/responses/'+((isWebView?)?'webview/':'')+'{pathParams...}'
Option 2:
Put the /webView conditionally on server side inside the {pathParams...} variable

Categories