How can I add a dynamic “active” CSS class to the navigation on any given page?

Asked by Last Modified  

1 Answer

Learn CSS

Follow 1
Answer

Please enter your answer

To dynamically add an "active" CSS class to the navigation menu based on the current page, you typically need to determine the active page within your application and conditionally apply the "active" class to the corresponding navigation link.Here's a general example using vanilla JavaScript for a simple...
read more
To dynamically add an "active" CSS class to the navigation menu based on the current page, you typically need to determine the active page within your application and conditionally apply the "active" class to the corresponding navigation link.Here's a general example using vanilla JavaScript for a simple scenario:```html<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> /* Your basic navigation styles */ nav { background-color: #333; padding: 10px; } nav a { color: white; text-decoration: none; padding: 5px; margin: 0 10px; } /* Active link styles */ nav a.active { background-color: lightcoral; } </style> <title>Dynamic Active Class</title></head><body> <nav> <a href="/" id="homeLink">Home</a> <a href="/about" id="aboutLink">About</a> <a href="/contact" id="contactLink">Contact</a> </nav> <script> document.addEventListener('DOMContentLoaded', function () { // Get the current page URL const currentPageUrl = window.location.pathname; // Get all navigation links const navLinks = document.querySelectorAll('nav a'); // Loop through each link and check if it matches the current page navLinks.forEach(function (link) { const linkUrl = link.getAttribute('href'); if (currentPageUrl === linkUrl) { // Add the "active" class to the matching link link.classList.add('active'); } }); }); </script></body></html>```In this example:- The JavaScript code runs when the DOM is fully loaded (`DOMContentLoaded` event).- It retrieves the current page URL using `window.location.pathname`.- It loops through each navigation link and compares its `href` attribute with the current page URL.- If a match is found, the "active" class is added to the corresponding navigation link.This is a basic example, and in a more complex application or framework (such as Angular, React, or Vue.js), you may have more advanced routing mechanisms that handle this for you. If you are using a specific framework, let me know, and I can provide more targeted guidance. read less
Comments

Related Questions

DIFFERENCE BETWEEN VISIBILITY HIDDEN AND DISPLAY NONE
Visibility Hidden and Display None Basically Does two different thing. Display None Hides Element but Does not occupy any space, Visibility Hidden Hides Element but takes up Space which affects layout
Maheskumar
How do you connect a CSS styling sheet to an HTML page?
Using internal Css and Inline Css.
Asif
0 0
5
What is a CSS File? It is used for what purpose?
Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in HTML or XML (including XML dialects such as SVG, MathML or XHTML). CSS describes how elements...
Pravin
0 0
5
What is the best text editor for writing HTML and CSS?
Best Text Editors for HTML & CSS 1. VS Code -- Fast, extensions, IntelliSense. 2. Sublime Text -- Lightweight, fast, multi-cursor editing. 3. Atom -- Open-source, customizable (discontinued...
Janardan
0 0
5
How do you create a box filled with a color with HTML / CSS?
o create a box filled with color in HTML/CSS, we will be using HTML div tag. We have used div tag to create structure of box. Then we have used CSS height and width property to set the dimension of rectangle
Radha
0 0
5

Now ask question in any of the 1000+ Categories, and get Answers from Tutors and Trainers on UrbanPro.com

Ask a Question

Related Lessons

Bootstrap grid system
What is a Grid? As put by wikepedia − In graphic design, a grid is a structure (usually two-dimensional) made up of a series of intersecting straight (vertical, horizontal) lines used to structure...

Kick start your IT career with User Interface development
If you are planning to start your career into IT, you can begin as User Interface developer. No previous IT background or programming experience needed. Below are some of the responsibilties of User...


Awesome rotating Image on hover | HTML5, CSS3
Hello everyone let's see how to make an awesome rotating image on hover with HTML 5.0 and CSS 3.0. STEP 1: In HTML code put an image with the HTML tag STEP 2: Style that image however you want. Below...

CSS awesome tips
CSS - Cascading Style Sheet is used to beautify Web pages and there are some common things which are very basic yet conceptual and very important for development. So here are some of the important tips...

Recommended Articles

Since the world today is ruled by the Internet, everyone desires to build a website for either business or personal interests. HTML or Hyper-text Mark-up Language is a globally standardized language which used to format web pages. By using HTML, the appearance of text, links, images and almost every part of a web page could...

Read full article >

Today, no business can exist without having its own website to interact with its customer base. Having a website is no more restricted to the big MNCs. With the advancement in technology and global business, even the small enterprises are spending on having their own websites and development teams. The person works on web...

Read full article >

Almost all of us, inside the pocket, bag or on the table have a mobile phone, out of which 90% of us have a smartphone. The technology is advancing rapidly. When it comes to mobile phones, people today want much more than just making phone calls and playing games on the go. People now want instant access to all their business...

Read full article >

Business Process outsourcing (BPO) services can be considered as a kind of outsourcing which involves subletting of specific functions associated with any business to a third party service provider. BPO is usually administered as a cost-saving procedure for functions which an organization needs but does not rely upon to...

Read full article >

Looking for CSS Training?

Learn from the Best Tutors on UrbanPro

Are you a Tutor or Training Institute?

Join UrbanPro Today to find students near you