Published 6/19/2020 ยท 1 min read
Tags: javascript
Using JavaScript To Access URL Segments
Whilst working on a recent project, I wanted an accordion navigation to remain open depending on what the category segment in the url was displaying. To do this I found a simple bit of JavaScript published on CSS-Tricks which looks like this:
Get the full URL path:
const newURL =
window.location.protocol +
"://" +
window.location.host +
"/" +
window.location.pathname;
Next split the segments of the URL using:
const pathArray = window.location.pathname.split("/");
Finally select the segment you require using:
const segment_1 = pathArray[1];
The above code would select segment_1 but you can see how you can easily select segment_2,segment_3 etc.
Once these segments are stored in variables it is really easy to set states for your navigation.
const nav = document.getElementById("nav");
if (segment_2 === "category") {
nav.querySelector("li ul:not(:first-child)").classList.add("is-hidden");
}
If you like this article and want to learn more about Javascript, I have started a series of posts on CodPen.
Related Articles
- Compressed NFTs: Collections, Verification, and Building a Claim Page
Taking our cNFT minting system to production: creating verified collections, building a web-based claim flow, and preparing for mainnet deployment.
- Building Compressed NFTs on Solana with Generative SVG Art
A practical guide to creating and minting compressed NFTs (cNFTs) on Solana using Metaplex Bubblegum, with animated SVG artwork generated from wallet addresses.
- Learn Svelte & SvelteKit: Course Overview
A complete beginner's guide to Svelte and SvelteKit. From reactivity basics to full-stack applications, learn the framework that compiles away.