By Sam Deering

jQuery Get Current Page URL

By Sam Deering

jQuery code snippet to get the current web page full url and store it in a variable for use with other scripts. This is the url you see in your address bar.

$(document).ready(function() {

	//pure javascript
	var pathname = window.location.pathname;
	// to show it in an alert window

There is also this function that may help when determining absolute paths.

function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + + loc.hash).length - pathName.length));
  • Mehmood

    My problem solved

  • Vignesh Lakshmanan

    Thanks a lot
    I got a solution for my code from yours thanks…………….

  • vicosoft

    thanks, it worked. The problem is solved

  • Jesús Velasco Campos

    thanks, great work!

  • D Dub

    Sam… You have helped me out more times than I can count, thank you. I was wondering if you had an example of how to create the “Plain” code popup that you have on your code samples. I don’t want to use FLASH, but when the popup opens it needs to have code that was dynamically created when the page loaded (it includes the current pages URL). Any suggestions? Thanks in advance for your help.

  • thanks! It works great.

  • Hey, Sam! Thanks for that. The jQuery snippet works brilliantly.

    What I’m now trying to implement is a way to apply CSS to the element on the current page whose ID matches the hash fragment of the url. Essentially, I’m working on a website with a fixed header (height: 117px) and I want each anchor to show below the header… not behind it.

    Could you give me some help with that?

    Many thanks in advance. I look forward to your reply.

    • So I assign the current url to a variable:
      var x = $(location).attr(‘href’);

      Then convert the value of x to an array and assign it to y:
      var y = x.split(‘#’);

      That’s half of the challenge, sorted… #time4bed

      • Hi mate, can you send me in the direction of the code, and i’ll take a look for you.

        • Unfortunately (for me), I’m working locally on the website… so I won’t be able to.

          • Found new friends in .position() and .offset()… the quest to conquer continues. #time4bed

          • ok no worries

        • Hey, Sam!

          I’ve been given permission to make the site live, with login permission. Please send me your email address so I can send you the URL and some temporary login details.


  • Tuan

    Thank you Sam, you help me.

  • fsd


Get the latest in JavaScript, once a week, for free.