Home  >  Article  >  Web Front-end  >  How to Retrieve and Use a URL Query String Parameter with jQuery?

How to Retrieve and Use a URL Query String Parameter with jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 00:54:13711browse

How to Retrieve and Use a URL Query String Parameter with jQuery?

Retrieving Query String from URL Using jQuery

To extract the value of the "location" parameter from the URL provided ("http://www.mysite.co.uk/?location=mylocation1") and use it in jQuery code, follow these steps:

First, define a JavaScript function to parse the URL parameters:

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Next, use the getUrlVars() function to extract the "location" value:

var locationValue = getUrlVars()['location'];

Now, you can utilize the extracted value in your jQuery code:

$('html,body').animate({ scrollTop: $('#div#' + locationValue).offset().top }, 500);

This will scroll the page to the element with the ID corresponding to the "location" value, as specified in the selector (e.g., "#div#mylocation1").

The above is the detailed content of How to Retrieve and Use a URL Query String Parameter with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn