JavaScript Location

Working with URLs and page navigation

🌐 What is the Location Object?

The Location object contains information about the current page URL and provides methods to navigate to different pages or reload the current page.


// Get current page URL
console.log(location.href);

// Get hostname (domain)
console.log(location.hostname);

// Get pathname (page path)
console.log(location.pathname);

// Get search parameters
console.log(location.search);
                                    

Current Page Info:

Click the button to see current page location

Location Properties

🔗

href

Complete URL of current page

location.href
// "https://example.com/page.html"
🏠

hostname

Domain name of the website

location.hostname
// "example.com"
📁

pathname

Path part of the URL

location.pathname
// "/page.html"
🔍

search

Query string parameters

location.search
// "?name=john&age=25"

🔹 Navigation Methods

Use location methods to navigate and reload pages:

// Navigate to a new page
location.href = "https://example.com";

// Or use assign method
location.assign("https://example.com");

// Replace current page (no back button)
location.replace("https://example.com");

// Reload current page
location.reload();

// Reload from server (ignore cache)
location.reload(true);

Try these (be careful - they will navigate!):

🔹 URL Parts Breakdown

Understanding different parts of a URL:

// Example URL: https://example.com:8080/path/page.html?name=john&age=25#section1

console.log(location.protocol);  // "https:"
console.log(location.hostname);  // "example.com"
console.log(location.port);      // "8080"
console.log(location.pathname);  // "/path/page.html"
console.log(location.search);    // "?name=john&age=25"
console.log(location.hash);      // "#section1"
console.log(location.host);      // "example.com:8080"
console.log(location.origin);    // "https://example.com:8080"

URL Structure:

protocol://hostname:port/pathname?search#hash

  • protocol: http:, https:, file:, etc.
  • hostname: Domain name (example.com)
  • port: Port number (80, 443, 8080, etc.)
  • pathname: Path to the page (/folder/page.html)
  • search: Query parameters (?key=value&key2=value2)
  • hash: Fragment identifier (#section)

🔹 Working with Query Parameters

Extract and work with URL parameters:

// Get URL parameters
function getUrlParameter(name) {
    const urlParams = new URLSearchParams(location.search);
    return urlParams.get(name);
}

// Example usage
// URL: page.html?name=John&age=25&city=NewYork
console.log(getUrlParameter('name'));  // "John"
console.log(getUrlParameter('age'));   // "25"
console.log(getUrlParameter('city'));  // "NewYork"

// Get all parameters
function getAllParameters() {
    const params = new URLSearchParams(location.search);
    const result = {};
    for (let [key, value] of params) {
        result[key] = value;
    }
    return result;
}

console.log(getAllParameters());
// {name: "John", age: "25", city: "NewYork"}

Try this:

🔹 Practical Examples

Common use cases for the location object:

🔸 Redirect Based on Condition

// Redirect mobile users
if (screen.width < 768) {
    location.href = "mobile-version.html";
}

// Redirect if not logged in
if (!localStorage.getItem('userToken')) {
    location.href = "login.html";
}

🔸 Auto-refresh Page

// Refresh page every 30 seconds
setTimeout(function() {
    location.reload();
}, 30000);

// Refresh with countdown
let countdown = 10;
const timer = setInterval(function() {
    console.log("Refreshing in " + countdown + " seconds...");
    countdown--;
    if (countdown < 0) {
        clearInterval(timer);
        location.reload();
    }
}, 1000);

🔸 Dynamic Navigation

// Navigate based on user choice
function navigateToSection(section) {
    switch(section) {
        case 'home':
            location.href = 'index.html';
            break;
        case 'about':
            location.href = 'about.html';
            break;
        case 'contact':
            location.href = 'contact.html';
            break;
        default:
            location.href = 'index.html';
    }
}

🧠 Test Your Knowledge

What's the difference between location.assign() and location.replace()?