Customize Link Appearance Depending on Current Section

Looking for a way to dynamically change the color of navigation links based on which section of the page a user is currently viewing? Here's an example setup:

<div id="topNav">
     <ul>
          <li><a href="#contact">Contact</a></li>
          <li><a href="#web_design">Web Design</a></li>
          <li><a href="#home">Home</a></li>
     </ul>
</div>

<div id="home">
     <img src="images/dog.jpg" class="bg" />
</div>
<div id="web_design">
     <img class="titleImage" src="images/web_design.jpg" />
</div>
<div id="contact">
     <img class="titleImage" src="images/contact.jpg" />
</div>

To achieve this, you can use a CSS class "selected" on list items corresponding to the current section like so:

#topNav li.selected a {
    color: #cbcacc;
}

Your menu will now update its link colors based on the user's location on the page. Hope this helps!

Answer №1

Consider utilizing a tool known as scrollspy. Various resources can be found online:

If you need more information, try searching with the keyword scrollspy.

The following code is from the above jsFiddle:

JS

// Selectors
var lastId,
    topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    
    menuItems = topMenu.find("a"),
   
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Click handler for fancy scroll animation
menuItems.click(function(e){
  var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
  $('html, body').stop().animate({ 
      scrollTop: offsetTop
  }, 300);
  e.preventDefault();
});

// Scroll binding
$(window).scroll(function(){
   
   var fromTop = $(this).scrollTop()+topMenuHeight;

  
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";

   if (lastId !== id) {
       lastId = id;
       
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }                   
});

HTML

<div id="topNav">
     <ul>
          <li><a href="#contact">Contact</a></li>
          <li><a href="#web_design">Web Design</a></li>
          <li><a href="#home">Home</a></li>
     </ul>
</div>
<div class="spacer"></div>
<div id="home">
     <img src="images/dog.jpg" class="bg" />
</div>
<div id="web_design">
     <img class="titleImage" src="images/web_design.jpg" />
</div>
<div id="contact">
     <img class="titleImage" src="images/contact.jpg" />
</div>

CSS

#topNav {
    width: 100%;
    height: 60px;
    position: fixed;
    top: 20px;
}

div.spacer {
    height: 80px;
}

#topNav li.selected a {
    color: #cbcacc;
}

Answer №2

One fascinating selector in CSS3 is :target, which allows you to style your links based on their targets. An example of how to use it can be seen below:

:target{color:#ff0000;}

For more information on the CSS3 target selector, consider searching on Google.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the visibility of a button based on a checkbox in JavaScript - here's how

Just starting out with JS and working on a react project. I need to toggle the visibility of a button from false to true when a checkbox is checked. Here's my code, I believe the logic is correct but it's not updating the UI. Any suggestions are ...

Manipulating the DOM with AngularJS directives is not functioning as expected

I am facing an issue with integrating a code that needs to scroll slowly on the page using AngularJS 1.4. When I try to include this code in a directive using the link function(scope, element, attrs), it doesn't work properly. Interestingly, the code ...

Is it possible to use tabs.create to generate a tab and then inject a content script, where the code attribute is effective but the file attribute seems to be ineffective

I am currently facing an issue with injecting a content script file into a newly created tab. The problem lies in the fact that I keep receiving an error stating chrome.tabs.executeScript(...) is undefined in the console output of the Popup. It may be wort ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...

Trouble with targeting a specific css class

Can someone help me with a CSS issue I'm experiencing? Here is my code: <div class='test'> <div>test 1</div> <div>test 2</div> </div> <div class='test'> <div>test 3&l ...

Changing the font-family to 'Symbol' and using Windows-1252 character encoding

I have a collection of HTML documents that contain basic text encoded in Windows-1252, but scattered throughout the content are various instances of span elements styled with font-family: Symbol. For instance: <span style='font-family:Symbol& ...

Tips for implementing a controlled RadioGroup in React: Mapping through an array of values to dynamically populate radio buttons

I have a scenario where I am utilizing a pre-defined set of arrays to populate multiple RadioGroups. The component hierarchy in the codesandbox is structured to resemble that of my actual project. Whenever I select a radio button, I receive an error messa ...

VueJS throws an error indicating that the object cannot be extended

I have encountered an issue while trying to update the promo object by adding a new field called colspan. Unfortunately, I am getting this error: uncaught (in promise) TypeError: Cannot add property colspan, object is not extensible at eval (eval at ...

Implementing a Fixed Navbar in VueJS on Scroll

I am seeking help with creating a Fixed Navbar on Scrolling using Vue.js. I initially wrote some jQuery code for this functionality, but now I want to transition it to Vue.js. The updated code can be found in a file named navbar.js. Previous jQuery CODE ...

disappearance of background image at bootstrap breakpoint

Hey there, I'm diving into a new journey in web design and I've encountered my first newbie issue. I'm attempting to place an image and text side by side on my web layout, but as soon as the breakpoint hits below 560px, the image disappears ...

JavaScript drag functionality is jerky on iPads, not seamless

I am currently attempting to implement a feature where I can drag a div (#drag) within its parent container (#container) using only pure JavaScript. This functionality is specifically required to work on iPad devices only. After writing a script that func ...

Jumping Iframe Anchor Link in Src

I'm facing a challenge with an iframe positioned in the center of a webpage. I want to show content from another page within the iframe, but not starting at the very top. To achieve this, I inserted an anchor into the src of my iframe, linked to an a ...

Tips on obtaining the element selector when a div is being dynamically loaded during an AJAX call

When running two ajax calls, I encounter an issue where the second call loads some HTML onto the page that is needed for processing a specific div in the first call. However, since the div is not present until after the second call is completed, I receiv ...

What is the correct way to establish and terminate a MongoDB connection in a Node.js application?

Hey everyone, I have a piece of code at this link (https://github.com/MrRav3n/Angular-Marketplace/blob/master/server.js) and I'm curious if I am properly starting and ending my database connection. Should I connect and end the db connection in every a ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

Is it possible to invoke an AngularJs service by clicking a button?

Recently, I've been working on some AngularJS code involving a service and controller. angular.module('myModule', []).service("AttendanceService", function ($http) { this.getdata = function () { return $http({ ...

When hovering, the CSS border-bottom should extend

I am looking to create an animated border effect. When hovering over the link, I want the border-bottom to extend seamlessly from left to right. After much searching, I am still unsure what this effect is called. Below is the code I have: .a{ width ...

BASH-SHELL SCRIPT: Display a specific portion of content from a file

Recently, I stumbled upon a text file containing a snippet of HTML code: >>nano wynik.txt which includes the following text: 1743: < a href="/currencies/lisk/#markets" class="price" data-usd="24.6933" data-btc= "0.00146882" My goal is to extr ...

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

Updating a specific field within an array in a Meteor object using MongoDB

I have a document with game details and participants. Here is an example of the structure: { "gameName":"Shooter", "details":[ { "submitted":1415215991387, "author":"XYZ", "subPlayer":{ "members":{ ...