jQuery Get Current Page URL on Button Click

In this tutorial, learn how to get current page URL by clicking on the button in jQuery. The short answer is to use the code snippet $(location).attr('href') to get the current page’s full URL. The current page URL is the URL you can find in the address bar.

The current URL in the address bar is the absolute path. When you see the address bar, you can find the URL which is the current location that you have to get using jQuery.

Let’s find out how to find the current and the base URL of the page with the examples given below.

How to Get Current Page URL on Click Using jQuery

To get the current Page URL, you have to use the code snippet $(location).attr('href') of jQuery. See the example given below to learn the method of getting the current URL.

Output



Click the above button to find the URL of the current page. The current page URL is the URL you can find in the address bar. You will get an alert message with the click of the button. The alert message contains the URL or location of the current page.

Get Path URL of Current Page on Button Click Using jQuery

If you want to get only the path and not the full URL of the current page, you have to use $(location).attr('pathname'). The pathname is used here within the attr() function to get the path and not the full URL.

Output



When you click the button given above, you will get only the path of your website given in the address bar. It does not contain the base URL of the page.

How to Find Base Link of the Page

To find the base link of the page, you have to use $(location).attr('origin') method of jQuery. The origin value of the attr() function indicates that you want to find the base URL of the current page.

Output



You have to click the button given above to find the base link of the page. So, with the above example, you can find the current, path, and the base URL of the page.

You May Also Like to Read.

I hope you like this tutorial on how to get the URL of the current page in jQuery.