Last Updated on August 10, 2022 by Roshan Parihar
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.
1 2 3 4 5 6 7 8 9 |
<script type="text/javascript"> $(document).ready(function(){ $('#btnGetURL').click(function(){ var currentURL = $(location).attr('href'); alert(currentURL); }); }); </script> <button type="button" id="btnGetURL">Get Current URL</button> |
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.
1 2 3 4 5 6 7 8 9 |
<script type="text/javascript"> $(document).ready(function(){ $('#btnGetURL').click(function(){ var currentURL = $(location).attr('pathname'); alert(currentURL); }); }); </script> <button type="button" id="btnGetURL">Get Path URL</button> |
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.
1 2 3 4 5 6 7 8 9 |
<script type="text/javascript"> $(document).ready(function(){ $('#btnGetURL').click(function(){ var currentURL = $(location).attr('origin'); alert(currentURL); }); }); </script> <button type="button" id="btnGetURL">Get Base URL</button> |
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.
- How to get selected checkbox value using jQuery
- Remove string spaces and dash using jQuery
- Count string characters length using jQuery
- how to get selected checkboxes id on click using jQuery.
I hope you like this tutorial on how to get the URL of the current page in jQuery.