About

Labels

slider

Recent

Navigation

Function based on window location hash


Now we all know that on click of a link who points to a div (adding id in href tag) will update the window.location.hash and the id of that particular div will be added in the end of the current location. But have you ever noticed that some sites have multiple tabs on click of any tab it updates the location and on refresh of page it opens the same tab.
So what makes the window location with hashes so important and how to perform those functions.

Well, to access the current hash of a location we use
window.location.hash
This one returns the current hash value from the location. Let's say the current location is:
http://abc.com/#tab1 
The return value would be #tab1. To make the functions based on that we're going to use them in if conditions. But what we are going to do is to remove first # from it, because I found that some browsers return window.location.hash value with # or without it. Lets remove it by replace function.
var x=window.location.hash.replace('#',''); 
If the current location contain #, that will be removed. Now we can access them like this:
if(x=='tab1'){
// Using jQuery
$('#tab1').addClass('active');
}
This one is just a glance of what can be done using window.location.hash. Further many stuff can be performed just need time to code them.

I found this has been used in popups, tabs, accordions, scroll to stuff and many more. Try it, if found something not clear comment below.
Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: