The Location Object
The
location
property of
a window is a reference to a Location object -- a representation
of the URL of the document
currently being displayed in that window. The
href
property of the
Location object is a string that contains the complete text of the
URL. Other
properties of this object, such as
protocol
, host
,
pathname
, and search
, specify
the various individual parts of the URL.
The search
property
of the Location object is an interesting one. It contains any portion
of a URL following (and including) a question mark. This is often some sort of
query string. In general, the question-mark syntax in a URL is a
technique for embedding arguments in the URL. While these arguments
are usually intended for CGI scripts run on a server, there is no
reason why they cannot also be used in JavaScript-enabled pages.
Example 13-5 shows the definition of a
general-purpose getArgs( )
function that you can use to extract
arguments from the search
property of a URL. It
also shows how this getArgs( )
method could have
been used to set initial values of the bouncing window animation
parameters in Example 13-4.
Example 13-5. Extracting arguments from a URL
/* * This function parses comma-separated name=value argument pairs from * the query string of the URL. It stores the name=value pairs in * properties of an object and returns that object. */ function getArgs( ) { var args = new Object( ); var query = location.search.substring(1); // Get query string var pairs = query.split(","); ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.