jquery - significance of .hash in this function - javascript

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

Related

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

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);
}
}
});

How to append another directory link to <a> in HTML

I am looking to create a simple following link to append to the current location.
Straight to examples
www.domain.com/link/address
link required
www.domain.com/link/address/newbit
I have tried the following so far:
<a href=#/newdir> //fail
result: www.domain.com/link/address#/newdir
<a href=/newdir> //fail
result: www.domain.com/newdir
<a href=./newdir> // fail
result: www.domain.com/link/newdir
So unless I have to use the trailing forward slash on the previous link, it appears this is actually not that easy.
Any suggestions welcome.
Thanks
P.S. I would like to do this without jQuery or Javascript if possible
That won't be possible if you do not prepend your base path with JavaScript or when the links are rendered server-side.
Prefixing the links with a / means look from the root, which is "http://www.domain.com".
EDIT : Check the base element on W3Schools. It will add a base path for all relatives URLs in the document.
EDIT 2 : If you are already on /adress/, #Adeneo's suggestion will obviously work.
append using jquery here is a sample code...
url
$(function(){
var current_location='www.domain.com/link/address';
$("#url").attr('href',current_location+"/newbit");
});
If www.domain.com/link/address is the page that you are already on, then
newdir
would be enough, resulting in www.domain.com/link/address/newdir address.
If not, you should use JS.
I think you can do this in a clever way , you just have to add a jQuery function that gets the href value and redirect where you want after processing. like this
$("a").click( function () {
var href = $(this).attr("href");
// the variabel href is everything inside the attribut href
location.href = "http://domain/" + href ;
});

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;
);

How to activage class based on anchor tag #id in URL

A while ago I noticed a page that highlighted certain areas of the page by getting the #some_random_id from the url.
for instance /mypage-destination/#codex_destination_5 would obviously drop you down to the page area in question, but then highlight the area so you don't miss it.
I looked into it, and I cannot seem to find the way to extract a URL property # anchor destination.
document.getElementById(window.location.hash.substring(1)).style.backgroundColor = "#aaa";
You can use window.location.hash to get the id linked in the URL(which would return #codex_destination_5 using your example).
You can then use substring(1) to omit the hash symbol(#codex_destination_5 becomes codex_destination_5).
Using this as the id would be the next logical step.

jQuery if url hash, click event/activate javascript

So from the home page, i have a link that goes to a products listing page.
The product page has expand/collapse divs.
I need the appropriate div to expand depending on what the url# is.
So the link on the homepage is
healthy snacks
when i click the link above, i am trying to activate this, on the product page:
Healthy Snacks
I've tried some of the other codes that i found that trigger click by checking for hash tag and none of them were working properly, i think it's because of the ReverseDisplay js.
Please any insight would help.
thanks
You can make the following changes in the document ready function of your product page:
Simple fix: Since the jQuery id-selector is #elementId, you can simply use the window.location.hash value as your id selector, and use it to target the desired element.
if ( window.location.hash ) {
$(window.location.hash).click(); //clicks on element specified by hash
}
Better: In addition to the above, take the js out of your markup.
$('#healthysnacks').click(function(e) {
e.preventDefault();
ReverseDisplay('products4');
});
Then, after doing this, use the $(window.location.hash).click() code from above.
Also, change your link to:
Healthy Snacks
You can use the hash property of the Location object, try the following:
$(document).ready(function(){
var id = window.location.hash;
$(id).trigger('click')
})
As you are using jQuery instead of using javascript: protocol, you can use the jQuery click method:
$('#healthysnacks').click(function() {
// do something here
})
The answers suggested here are valid, but...
Be extremely careful when using the window.location.hash as it is in a jQuery selector because this could lead to a XSS vulnerability. $() can also create an HTML element and with a carefully constructed hash value, someone could execute arbitrary JavaScript code.
For example
http://my-website.com/about#'><img src=x onerror=alert(/XSSed/)>
If my-websites.com/about page uses the window.location.hash inside a jQuery selector, that onerror code would end up getting executed.

Categories