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

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

JQuery Challenge: Solving Dynamic Modal Issues

I'm in the process of creating a webpage that features multiple divs, each with its own unique image and title. Within each div, there's a button that, when clicked, should grab the specific image and title and display them in a modal. However, I ...

Only initiate an AJAX call if there are no other pending AJAX requests from prior function invocations

Arriving at a new, chaotic code base with no testing available has presented me with a significant challenge. I am currently struggling to resolve an issue without the use of ES6, only relying on plain vanilla JS and jQuery. The scenario: Within a web pag ...

Techniques for verifying phone numbers from various countries

The number of digits in a mobile number differs from country to country. I have tried using regular expressions, however, for example, India allows 10 digits, but this does not validate UAE, where the number of digits can range from 7 to 9. ...

Inserting a large number of records in MySQL using a batch insertion method

Currently, I am facing an issue with inserting multiple records into a MySQL table at once. Just so you know, I am using Node.js along with MySQL (you can find more information about it here: https://www.npmjs.com/package/mysql) Here is what I have been ...

What is the best way to execute a function before showing an alert in a $.post() callback?

Just to clarify, the code I'm working with is not original to me; I am simply making some interface adjustments using a plugin for an existing system. The task at hand involves creating a plugin that utilizes blockUI (yes, a plugin within a plugin) t ...

How can I create a jQuery Listener for 2 different events simultaneously?

One issue I am facing is triggering a function when an event occurs in a table cell or when an item is selected from a dropdown menu. Currently, I have code that works for the table cell event: $('td[id^="tblcell"]').click(function() { ... ... d ...

Get rid of the spaces in web scraping <tr> tags using Node.js

I've encountered a problem that goes beyond my current knowledge. I'm attempting to web-scrape a specific webpage, targeting the <tr> element in nodejs. Although I can successfully retrieve the content, it seems that the format is not as cl ...

Converting jQuery selectors into JSON objects

I would like to create a JSON object from a jQuery selector string, which is the text inside $(), without actually selecting elements from the DOM. Is there a built-in function in jQuery that can achieve this task or are there any open-source libraries ava ...

Can a rotationX be applied within an existing rotationX?

I have a collection of 3 divs labeled a, b and c inside a container. The container is rotatedX by 90 degrees, giving the appearance that it is "lying on its back". Now, I am trying to rotate the a, b, and c divs so they appear to be "standing up" again. Ho ...

How can I establish the conversion from pixels to em units?

According to a source I found, 1 em is equivalent to 16px. You can read more about it here. Despite setting the font-size to 100% in the body and using font-size: 1em, the standard font size in my Jekyll site remains 12px. Curious? Visit my Jekyll site a ...

Error: Unable to access the `insertUsername` property as it is not defined

When I attempt to submit the login form created by the new.ejs file, instead of being redirected to the expected page, I am encountering an error message that reads: Cannot read property 'insertUsername' of undefined This same error message is ...

Is there a way to make images load only when the navigation buttons are clicked in a scrollable (jquery tools) rather than loading all images at once?

I came across this great demo tutorial that I'm currently following: The issue with the tutorial is that it loads all the images at once, which significantly impacts performance. My goal is to have it load a set of images each time you click the arro ...

Kendo Grid with locked height

Using a grid with some elements locked, we have established a CSS-defined minimum and maximum height for the grid. .k-grid-content { max-height: 400px; min-height: 0px; } An issue arises when setting the height of the locked grid. If the grid&a ...

Multiple callbacks triggered by jQuery CSS transitions

I am experiencing an issue with my menu animation. I am curious as to why the slideDown transition is occurring twice. You can view the JSFiddle here. <ul class=top-menu"> <li>Item 1</li> <li>Item 2</li> <ul cl ...

Integrating PHP and Ajax for form submission can be enhanced by

Exploring the PHP and jQuery Ajax approach for creating a simple login system. I am aiming to use ajax to submit parts of a form and receive an array as a response. I am still unsure if my implementation is correct. Below is the PHP code snippet: if($ac ...

Discovering, storing, and displaying JSON data in JavaScript

I am currently working on a PHP file called rows2.php that displays results from a database by showing the new id of the field in this format: {'new_id':'92'} My goal is to use JavaScript to load this data and add the new_id surrounded ...

Adjust the href attribute of a link dynamically using the value input from a text field immediately

Is there a way to dynamically change the href attribute of a link when a user types in an input field? And is it possible to detect when a user pastes content into the input field as well? Would appreciate any suggestions on how to accomplish this using j ...

Relocate the HTML checkbox to the left side of its width

I need an answer that utilizes only CSS, without any JavaScript. In a form, I have a checkbox as follows: <label for="autologin">Remember Me</label> <input type="checkbox" class="checkbox" id="autologin" name="autologin" value="1"> <d ...

Problems with IE8 - Rendering correctly on all other browsers

I'm having some trouble with my website's display in IE8. It looks great in IE9, Firefox, and Chrome, but in IE8 it appears all jacked up. I'm using WordPress with Thesis Themes and editing custom.css for my changes. You can view my site he ...