8 Useful jQuery Techniques For URLs

rmally we use Server side scripts like PHP, ASP, C# to retrieve the information required about our Page URL, QueryString and Hash Parameter. But amazingly it can also be done using Javascript or jQuery too. It can be very handy considering the speed of program as well as ease in programming.
The following are examples of useful code snippets which we can directly use.

1. Get the Current Page URL

A very simple snippet, which stores the current page URL in a variable:

// Retrieve current URL
var url = document.URL;

2. Get the Current Page Root URL

A very simple snippet, which stores the root URL in a variable:

// Retrieve root URL
var root = location.protocol + '//' + location.host;

3. Highlight Current Menu Item

Rather than manually modify navigation menus to add an “active” class to the current page we can use jQuery to identify which link contains the current URL which will save a lot of programming time:

var url = document.URL;
$('#menu a[href="'+url+'"]').addClass('active');

4. Page Redirect Using Javascript
If you need to redirect a page using jQuery:

// Redirect - insert required URL
window.location.href = "https://itswadesh.wordpress.com/";

5. Get Querystring Parameters of the Current Page

If the URL contains a querystring with multiple parameters the following snippet will parse each parameter and store the array as a variable:

var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}

To use any of the parameters you can access the value using the parameter name. E.g. if the URL contains the querystring “?a=3&b=2&c=1″ you can access the value for “a” using:

// Will alert the value of parameter a
alert(vars['a']);

6. Get the URL Hash Parameter

Retrieve a hash parameter and store in a variable:

// Get # parameter
var param = document.URL.split('#')[1];

7. Change Browser Address Bar Hash Parameter

In the example below we replace the hash parameter, which we get from the clicked link. Useful for adding bookmarking capabilities when using AJAX:

// update browser address bar URL
$('a.demo-link').click(function(){
var hash = $(this).attr('href');
location.hash = hash;
});

8. Check If Link Contains External URL

The following snippet will check if a clicked link contains a URL to an external web page and if so, open in a new browser window:

var root = location.protocol + '//' + location.host;
$('a').not(':contains(root)').click(function(){
this.target = "_blank";
});

1 thought on “8 Useful jQuery Techniques For URLs

Leave a Comment

WhatsApp Logo Chat