JS Location Object 🎯

beginner
21 min

JS Location Object 🎯

Welcome to our comprehensive guide on the JavaScript Location object! In this tutorial, we'll delve into the world of web navigation and explore the powerful capabilities of the Location object. By the end of this lesson, you'll be able to navigate web pages like a pro. 💡 Pro Tip: This tutorial is designed for both beginners and intermediates, so let's get started!

Understanding the Location Object 📝

The Location object represents the current URL of the document. It provides various properties and methods to manipulate the URL and navigate within a web page.

Properties of the Location Object 📝

  • href: This property returns the complete URL of the current document.
  • protocol: It returns the protocol part of the URL (e.g., http: or https:).
  • host: This property returns the host part of the URL (e.g., example.com).
  • hostname: It returns only the hostname part of the URL (e.g., example).
  • port: This property returns the port number (if specified) of the URL.
  • pathname: It returns the path part of the URL (e.g., /path/to/file).
  • search: This property returns the search parameters of the URL (e.g., ?param1=value1&param2=value2).
  • hash: It returns the hash part of the URL (e.g., #anchor).

Methods of the Location Object 📝

  • assign(url): It navigates the document to the specified URL.
  • reload(): It reloads the current document.
  • replace(url): It navigates the document to the specified URL without adding it to the history.

Practical Example 💡

Let's create a simple web page with JavaScript to demonstrate the Location object's capabilities.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Location Object Example</title> </head> <body> <h1>Location Object Example</h1> <button id="navigate">Navigate</button> <script> const button = document.getElementById('navigate'); button.addEventListener('click', () => { const url = 'https://www.codeyourcraft.com'; window.location.assign(url); }); </script> </body> </html>

In this example, we have a simple HTML page with a button. When clicked, the button navigates the page to CodeYourCraft's homepage using the Location object's assign() method.

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `Location` object represent in JavaScript?

Quick Quiz
Question 1 of 1

What does the `href` property of the `Location` object return?