π What is location?
The location object provides information about the current URL
and allows JavaScript to redirect, reload, or modify the browser URL.
π It is part of the BOM and accessed via window.location.
window.location === location // trueπ URL Structure
For this URL:
<https://www.example.com:8080/path/page.html?id=10#top>Property | Value |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
π§© Common location Properties
Example Taken:
https://www.example.com:8080/path/page.html?id=10#top
1οΈβ£ location.href
console.log(location.href);Explanation:
Returns the full URL of the current page.
https://www.example.com:8080/path/page.html?id=10#top2οΈβ£ location.protocol
console.log(location.protocol);Explanation:
Returns the protocol used.
https:3οΈβ£ location.hostname
console.log(location.hostname);Explanation:
Returns the domain name (no port).
www.example.com4οΈβ£ location.port
console.log(location.port);Explanation:
Returns the port number. Empty string if default (80 / 443).
80805οΈβ£ location.pathname
console.log(location.pathname);Explanation:
Returns the path after the domain.
/path/page.html6οΈβ£ location.search
console.log(location.search);Explanation:
Returns query parameters.
?id=107οΈβ£ location.hash
console.log(location.hash);Explanation:
Returns the URL fragment (used for anchors).
#top<div class="infographic-locationurl">
<style>
.infographic-locationurl {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--good: #1a8a5f;
--good-soft: #e1f2ea;
--mono-font: 'IBM Plex Mono', monospace;
--display-font: 'Fraunces', Georgia, serif;
box-sizing: border-box;
max-width: 880px;
margin: 0 auto;
font-family: 'Inter', system-ui, sans-serif;
color: var(--ink);
background: var(--paper);
overflow-x: hidden;
}
.infographic-locationurl[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--good: #4fbf8f;
--good-soft: #16281f;
}
.infographic-locationurl * { box-sizing: border-box; }
.infographic-locationurl h1 { font-family: var(--display-font); font-weight: 600; margin: 0; }
.infographic-locationurl p { margin: 0; }
.infographic-locationurl button { font-family: inherit; }
.lu-icon { width: 1em; height: 1em; display: inline-block; vertical-align: -0.15em; stroke: currentColor; flex-shrink: 0; }
.lu-wrap { padding: clamp(1.25rem, 5vw, 2.5rem) clamp(1.1rem, 5vw, 3rem) 2rem; }
.lu-hero { text-align: center; margin-bottom: 1.2rem; }
.lu-hero h1 { font-size: clamp(1.3rem, 4.5vw, 1.8rem); }
.lu-hero p { color: var(--ink-soft); margin-top: 0.4rem; font-size: 0.86rem; }
/* --- the URL bar itself --- */
.lu-urlbar { border: 1.5px solid var(--line); border-radius: 8px; background: var(--paper-alt); padding: 0.8rem 1rem; margin-bottom: 0.4rem; overflow-x: auto; }
.lu-url { font-family: var(--mono-font); font-size: clamp(0.72rem, 2.6vw, 0.92rem); white-space: nowrap; text-align: center; display: block; }
.lu-part { padding: 0.15rem 0; border-radius: 3px; cursor: pointer; transition: background 0.2s ease, color 0.2s ease; color: var(--ink-soft); }
.lu-part.is-active { background: var(--accent); color: #fff; }
.lu-punc { color: var(--ink-soft); }
/* --- legend list --- */
.lu-legend-list { max-width: 560px; margin: 0 auto 1rem; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
.lu-legend-row { display: flex; align-items: center; gap: 0.7rem; padding: 0.55rem 0.8rem; border-top: 1px solid var(--line); cursor: pointer; transition: background 0.15s ease; }
.lu-legend-row:first-child { border-top: none; }
.lu-legend-row:hover { background: var(--accent-soft); }
.lu-legend-row.is-active { background: var(--accent-soft); }
.lu-legend-name { font-family: var(--mono-font); font-size: 0.76rem; font-weight: 700; color: var(--accent); min-width: 140px; }
.lu-legend-desc { font-size: 0.76rem; color: var(--ink-soft); flex: 1; }
/* --- detail panel --- */
.lu-detail { max-width: 560px; margin: 0 auto; text-align: center; background: var(--paper-alt); border-left: 3px solid var(--accent); border-radius: 4px; padding: 0.8rem 1rem; }
.lu-detail-code { font-family: var(--mono-font); font-size: 0.78rem; color: var(--ink); margin-bottom: 0.35rem; }
.lu-detail-desc { font-size: 0.78rem; color: var(--ink-soft); margin-bottom: 0.5rem; }
.lu-detail-out { font-family: var(--mono-font); font-size: 0.8rem; color: var(--good); font-weight: 700; }
.lu-note { text-align: center; font-size: 0.8rem; color: var(--ink-soft); padding-top: 1.3rem; max-width: 560px; margin: 0 auto; }
.lu-note strong { color: var(--ink); }
@media (prefers-reduced-motion: reduce) {
.infographic-locationurl *, .infographic-locationurl *::before, .infographic-locationurl *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="lu-wrap">
<div class="lu-hero">
<h1>Anatomy of a URL</h1>
<p>Every location property is just a slice of the same string.</p>
</div>
<div class="lu-urlbar">
<span class="lu-url" id="luUrl">
<span class="lu-part" data-part="protocol">https:</span><span class="lu-punc">//</span><span class="lu-part" data-part="hostname">www.example.com</span><span class="lu-punc">:</span><span class="lu-part" data-part="port">8080</span><span class="lu-part" data-part="pathname">/path/page.html</span><span class="lu-part" data-part="search">?id=10</span><span class="lu-part" data-part="hash">#top</span>
</span>
</div>
<div class="lu-legend-list" id="luLegend">
<div class="lu-legend-row is-active" data-part="href">
<span class="lu-legend-name">location.href</span>
<span class="lu-legend-desc">the whole URL</span>
</div>
<div class="lu-legend-row" data-part="protocol">
<span class="lu-legend-name">location.protocol</span>
<span class="lu-legend-desc">the scheme used</span>
</div>
<div class="lu-legend-row" data-part="hostname">
<span class="lu-legend-name">location.hostname</span>
<span class="lu-legend-desc">the domain, no port</span>
</div>
<div class="lu-legend-row" data-part="port">
<span class="lu-legend-name">location.port</span>
<span class="lu-legend-desc">empty string if default (80/443)</span>
</div>
<div class="lu-legend-row" data-part="pathname">
<span class="lu-legend-name">location.pathname</span>
<span class="lu-legend-desc">the path after the domain</span>
</div>
<div class="lu-legend-row" data-part="search">
<span class="lu-legend-name">location.search</span>
<span class="lu-legend-desc">the query string</span>
</div>
<div class="lu-legend-row" data-part="hash">
<span class="lu-legend-name">location.hash</span>
<span class="lu-legend-desc">the fragment, used for anchors</span>
</div>
</div>
<div class="lu-detail" id="luDetail">
<div class="lu-detail-code">console.log(<span id="luDetailProp">location.href</span>);</div>
<div class="lu-detail-desc" id="luDetailDesc">Returns the full URL of the current page.</div>
<div class="lu-detail-out" id="luDetailOut">"https://www.example.com:8080/path/page.html?id=10#top"</div>
</div>
</div>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-locationurl')
|| document.querySelector('.infographic-locationurl');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') {
dark = true;
} else if (bodyAttr === 'false') {
dark = false;
} else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
const EXAMPLE = {
href: '"https://www.example.com:8080/path/page.html?id=10#top"',
protocol: '"https:"',
hostname: '"www.example.com"',
port: '"8080"',
pathname: '"/path/page.html"',
search: '"?id=10"',
hash: '"#top"'
};
const DESC = {
href: 'Returns the full URL of the current page.',
protocol: 'Returns the protocol used.',
hostname: 'Returns the domain name (no port).',
port: 'Returns the port number. Empty string if default (80 / 443).',
pathname: 'Returns the path after the domain.',
search: 'Returns query parameters.',
hash: 'Returns the URL fragment (used for anchors).'
};
const urlParts = wrapper.querySelectorAll('.lu-part');
const legendRows = wrapper.querySelectorAll('.lu-legend-row');
const detailProp = wrapper.querySelector('#luDetailProp');
const detailDesc = wrapper.querySelector('#luDetailDesc');
const detailOut = wrapper.querySelector('#luDetailOut');
function select(part) {
urlParts.forEach(p => p.classList.toggle('is-active', p.dataset.part === part));
legendRows.forEach(r => r.classList.toggle('is-active', r.dataset.part === part));
detailProp.textContent = 'location.' + part;
detailDesc.textContent = DESC[part];
detailOut.textContent = EXAMPLE[part];
}
urlParts.forEach(p => p.addEventListener('click', () => select(p.dataset.part)));
legendRows.forEach(r => r.addEventListener('click', () => select(r.dataset.part)));
select('href');
})();
</script>π location Methods
1οΈβ£ location.reload()
location.reload();Explanation:
Reloads the current page.
location.reload()β normal reloadlocation.reload(true)β force reload (from server)
Output:
π Page refreshes
2οΈβ£ location.assign()
location.assign("<https://google.com>");Explanation:
Navigates to a new URL
βοΈ Adds entry to browser history
Output:
β‘οΈ Redirects to Google
3οΈβ£ location.replace()
location.replace("<https://google.com>");Explanation:
Redirects to a new URL
β Does NOT add entry to history
Output:
β‘οΈ Redirects (Back button wonβt work)
<div class="infographic-locationmethods">
<style>
.infographic-locationmethods {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--good: #1a8a5f;
--good-soft: #e1f2ea;
--error: #c0392b;
--error-soft: #fbe9e7;
--mono-font: 'IBM Plex Mono', monospace;
--display-font: 'Fraunces', Georgia, serif;
box-sizing: border-box;
max-width: 880px;
margin: 0 auto;
font-family: 'Inter', system-ui, sans-serif;
color: var(--ink);
background: var(--paper);
overflow-x: hidden;
}
.infographic-locationmethods[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--good: #4fbf8f;
--good-soft: #16281f;
--error: #e57373;
--error-soft: #3a2222;
}
.infographic-locationmethods * { box-sizing: border-box; }
.infographic-locationmethods h1 { font-family: var(--display-font); font-weight: 600; margin: 0; }
.infographic-locationmethods p { margin: 0; }
.infographic-locationmethods button { font-family: inherit; }
.lm-icon { width: 1em; height: 1em; display: inline-block; vertical-align: -0.15em; stroke: currentColor; flex-shrink: 0; }
.lm-wrap { padding: clamp(1.25rem, 5vw, 2.5rem) clamp(1.1rem, 5vw, 3rem) 2rem; }
.lm-hero { text-align: center; margin-bottom: 1.2rem; }
.lm-hero h1 { font-size: clamp(1.3rem, 4.5vw, 1.8rem); }
.lm-hero p { color: var(--ink-soft); margin-top: 0.4rem; font-size: 0.86rem; }
.lm-code { background: #1e1e1e; color: #d4d4d4; border-radius: 5px; padding: 0.5rem 0.75rem; font-family: var(--mono-font); font-size: 0.68rem; line-height: 1.5; white-space: pre; overflow-x: auto; }
.tok-fn { color: #dcdcaa; }
.tok-str { color: #ce9178; }
.tok-punc { color: #d4d4d4; }
.tok-var { color: #9cdcfe; }
.lm-methods { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.6rem; margin-bottom: 1.2rem; }
.lm-method-col { display: flex; flex-direction: column; gap: 0.5rem; }
.lm-method-title { font-family: var(--mono-font); font-size: 0.74rem; font-weight: 700; text-align: center; color: var(--accent); }
.lm-method-desc { font-size: 0.7rem; color: var(--ink-soft); text-align: center; line-height: 1.4; min-height: 2.6em; }
.lm-run-btn { border: none; background: var(--accent); color: #fff; padding: 0.42rem 0.6rem; font-size: 0.72rem; font-weight: 600; border-radius: 5px; cursor: pointer; }
.lm-run-btn:active { transform: scale(0.96); }
@media (max-width: 600px) {
.lm-methods { grid-template-columns: 1fr; }
}
/* --- mock browser --- */
.lm-page { border: 1.5px solid var(--line); background: var(--paper-alt); border-radius: 6px; overflow: hidden; margin-bottom: 1rem; }
.lm-page-bar { background: #2b2b2b; padding: 0.4rem 0.6rem; display: flex; align-items: center; gap: 0.5rem; }
.lm-page-dot { width: 8px; height: 8px; border-radius: 50%; background: #555; flex-shrink: 0; }
.lm-back-btn { border: none; background: #3a3a3a; color: #aaa; width: 20px; height: 20px; border-radius: 4px; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; margin-left: 0.3rem; }
.lm-back-btn:disabled { opacity: 0.35; cursor: not-allowed; }
.lm-back-btn .lm-icon { width: 12px; height: 12px; }
.lm-refresh-icon { width: 12px; height: 12px; color: #aaa; margin-left: auto; }
.lm-refresh-icon.is-spinning { animation: lm-spin 0.6s linear; }
@keyframes lm-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
.lm-page-body { padding: 1.1rem 1.2rem; background: var(--paper); }
.lm-current-url { font-family: var(--mono-font); font-size: 0.8rem; text-align: center; margin-bottom: 0.9rem; padding: 0.4rem 0.6rem; background: var(--paper-alt); border-radius: 5px; transition: background 0.3s ease; }
.lm-current-url.lm-flash { background: var(--accent-soft); }
.lm-stack-label { font-family: var(--mono-font); font-size: 0.64rem; color: var(--ink-soft); margin-bottom: 0.4rem; }
.lm-stack { display: flex; flex-direction: column-reverse; gap: 0.3rem; }
.lm-stack-entry { font-family: var(--mono-font); font-size: 0.72rem; padding: 0.35rem 0.6rem; border: 1px solid var(--line); border-radius: 4px; background: var(--paper); color: var(--ink-soft); display: flex; justify-content: space-between; transition: opacity 0.3s ease, background 0.3s ease, border-color 0.3s ease; }
.lm-stack-entry.is-current { border-color: var(--accent); color: var(--accent); font-weight: 700; background: var(--accent-soft); }
.lm-stack-entry.lm-entering { animation: lm-slide-in 0.35s ease; }
@keyframes lm-slide-in { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }
.lm-stack-entry.lm-replaced-flash { animation: lm-replace-flash 0.5s ease; }
@keyframes lm-replace-flash { 0% { background: var(--error-soft); } 100% { background: var(--accent-soft); } }
.lm-console-label { font-family: var(--mono-font); font-size: 0.66rem; color: var(--ink-soft); text-align: center; margin: 0 0 0.4rem; }
.lm-console { margin: 0 auto; max-width: 460px; text-align: left; border: 1.5px solid var(--line); background: #1e1e1e; padding: 0.55rem 0.75rem; font-family: var(--mono-font); font-size: 0.72rem; min-height: 2.6rem; max-height: 7em; overflow-y: auto; border-radius: 5px; }
.lm-console .lm-cline { display: block; opacity: 0; transform: translateY(-3px); transition: opacity 0.2s ease, transform 0.2s ease; margin-bottom: 0.12rem; }
.lm-console .lm-cline.is-shown { opacity: 1; transform: translateY(0); }
.lm-console-empty { color: #6b6b6b; font-style: italic; }
.lm-note { text-align: center; font-size: 0.8rem; color: var(--ink-soft); padding-top: 1.3rem; max-width: 580px; margin: 0 auto; }
.lm-note strong { color: var(--ink); }
@media (prefers-reduced-motion: reduce) {
.infographic-locationmethods *, .infographic-locationmethods *::before, .infographic-locationmethods *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="lm-wrap">
<div class="lm-methods">
<div class="lm-method-col">
<div class="lm-method-title">reload()</div>
<div class="lm-code"><span class="tok-var">location</span><span class="tok-punc">.</span><span class="tok-fn">reload</span><span class="tok-punc">();</span></div>
<div class="lm-method-desc">Reloads the current page. No history change.</div>
<button class="lm-run-btn" id="lmReloadBtn" type="button">run reload()</button>
</div>
<div class="lm-method-col">
<div class="lm-method-title">assign()</div>
<div class="lm-code"><span class="tok-var">location</span><span class="tok-punc">.</span><span class="tok-fn">assign</span><span class="tok-punc">(</span><span class="tok-str">"google.com"</span><span class="tok-punc">);</span></div>
<div class="lm-method-desc">Navigates away. βοΈ Adds a new history entry.</div>
<button class="lm-run-btn" id="lmAssignBtn" type="button">run assign()</button>
</div>
<div class="lm-method-col">
<div class="lm-method-title">replace()</div>
<div class="lm-code"><span class="tok-var">location</span><span class="tok-punc">.</span><span class="tok-fn">replace</span><span class="tok-punc">(</span><span class="tok-str">"google.com"</span><span class="tok-punc">);</span></div>
<div class="lm-method-desc">Navigates away. β No new history entry.</div>
<button class="lm-run-btn" id="lmReplaceBtn" type="button">run replace()</button>
</div>
</div>
<div class="lm-page">
<div class="lm-page-bar">
<div class="lm-page-dot"></div><div class="lm-page-dot"></div><div class="lm-page-dot"></div>
<button class="lm-back-btn" id="lmBackBtn" type="button" disabled title="back">
<svg class="lm-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 19-7-7 7-7"/><path d="M19 12H5"/></svg>
</button>
<svg class="lm-refresh-icon" id="lmRefreshIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg>
</div>
<div class="lm-page-body">
<div class="lm-current-url" id="lmCurrentUrl">codeveda.dev/lesson</div>
<div class="lm-stack-label">browser history stack (bottom = oldest)</div>
<div class="lm-stack" id="lmStack">
<div class="lm-stack-entry is-current" data-id="0">codeveda.dev/lesson</div>
</div>
</div>
</div>
<div class="lm-console-label">console</div>
<div class="lm-console" id="lmConsole"><span class="lm-console-empty">// try a method above</span></div>
</div>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-locationmethods')
|| document.querySelector('.infographic-locationmethods');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') {
dark = true;
} else if (bodyAttr === 'false') {
dark = false;
} else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
const currentUrlEl = wrapper.querySelector('#lmCurrentUrl');
const stackEl = wrapper.querySelector('#lmStack');
const backBtn = wrapper.querySelector('#lmBackBtn');
const refreshIcon = wrapper.querySelector('#lmRefreshIcon');
const consoleEl = wrapper.querySelector('#lmConsole');
let consoleCleared = false;
let stack = ['codeveda.dev/lesson'];
let idCounter = 0;
function log(text) {
if (!consoleCleared) { consoleEl.innerHTML = ''; consoleCleared = true; }
const line = document.createElement('span');
line.className = 'lm-cline';
line.textContent = text;
consoleEl.appendChild(line);
requestAnimationFrame(() => line.classList.add('is-shown'));
while (consoleEl.children.length > 6) consoleEl.removeChild(consoleEl.firstChild);
}
function renderStack(justEnteredIndex) {
stackEl.innerHTML = '';
stack.forEach((url, i) => {
const entry = document.createElement('div');
entry.className = 'lm-stack-entry' + (i === stack.length - 1 ? ' is-current' : '');
if (i === justEnteredIndex) entry.classList.add('lm-entering');
entry.textContent = url;
stackEl.appendChild(entry);
});
currentUrlEl.textContent = stack[stack.length - 1];
backBtn.disabled = stack.length <= 1;
}
function flashUrl() {
currentUrlEl.classList.add('lm-flash');
setTimeout(() => currentUrlEl.classList.remove('lm-flash'), 350);
}
wrapper.querySelector('#lmReloadBtn').addEventListener('click', () => {
refreshIcon.classList.remove('is-spinning');
void refreshIcon.offsetWidth;
refreshIcon.classList.add('is-spinning');
flashUrl();
log('π Page refreshes');
});
wrapper.querySelector('#lmAssignBtn').addEventListener('click', () => {
stack.push('google.com');
renderStack(stack.length - 1);
flashUrl();
log('β‘οΈ Redirects to Google β history entry added');
});
let replaceToggle = false;
wrapper.querySelector('#lmReplaceBtn').addEventListener('click', () => {
replaceToggle = !replaceToggle;
const target = replaceToggle ? 'google.com' : 'codeveda.dev';
stack[stack.length - 1] = target;
renderStack(null);
const currentEntry = stackEl.querySelector('.is-current');
if (currentEntry) {
currentEntry.classList.add('lm-replaced-flash');
setTimeout(() => currentEntry.classList.remove('lm-replaced-flash'), 500);
}
flashUrl();
log('β‘οΈ Redirects to "' + target + '" (replaced β back button won\u2019t return here)');
});
backBtn.addEventListener('click', () => {
if (stack.length <= 1) return;
stack.pop();
renderStack(null);
flashUrl();
log('β¬
back β "' + stack[stack.length - 1] + '"');
});
})();
</script>π assign() vs replace()
Method | Back Button |
|---|---|
| β Works |
| β Disabled |
π― Modify URL Parts
location.pathname = "/login";Explanation:
Changes path and reloads page.
Output:
β‘οΈ Navigates to /login
β Important Notes
locationcauses page reloadsChanging any property triggers navigation
Widely used for redirects & URL handling
β Summary
locationcontrols the URLUsed for redirects, reloads, and reading URL data
Part of BOM, under
window