Change the color of the text based on which classes the visitor is currently viewing on the page

I have a sidebar menu in plain html for page navigation, like this:

<div class="sidebar"><h2>About us</h2>

<h3><a href="#chapter1" class="link">Chapter 1</a></h3>
<h3><a href="#chapter2" class="link">Chapter 2</a></h3>
<h3><a href="#chapter3" class="link">Chapter 3</a></h3>
</div>

Currently, when a visitor clicks on Chapter 1, they are taken to the Chapter 1 section and the Chapter 1 link in the sidebar changes color temporarily due to a:active delay.

However, I am trying to find a way to have the link in the sidebar change color when the visitor is on the specific section. For example, when they scroll down to Chapter 2, the Chapter 1 link color should revert to normal and the Chapter 2 link color should change.

Any suggestions or solutions would be greatly appreciated!

Update: I am working with a Wordpress website, and the suggestions provided so far have not worked as the sidebar is a Wordpress sidebar with a fixed position.

Answer №1

Enhance your website with active and inactive styles

.active { color=red; }
.inactive { color=black; }

To activate chapters, include onMouseOver="setActive(1)", onMouseOver="setActive(2)", and so on...

Create a JavaScript function to adjust colors in the sidebar.

function setActive(ch)
{
   document.getElementById("#chapter1").className="link "+(ch==1?"active":"inactive");
   document.getElementById("#chapter2").className="link "+(ch==2?"active":"inactive");
   document.getElementById("#chapter3").className="link "+(ch==3?"active":"inactive");
}

Make sure to call setActive(xx) when clicking on any sidebar element.

Answer №3

Utilize Bootstrap's built-in breadcrumbs for easy navigation,

or check out this interactive example using jQuery: http://jsfiddle.net/8S2eu/2/

Here's the key script for implementation:

Organize the page structure as follows:

<div class="sidebar"><h2>About us</h2>

<h3><a href="#chapter1" class="link active" id="chapter1">Chapter 1</a></h3>
<h3><a href="#chapter2" class="link" id="chapter2">Chapter 2</a></h3>
<h3><a href="#chapter3"  class="link" id="chapter3">Chapter 3</a></h3>
</div>
<div class='main'>
    <section id="chapter1">
        <a id="chapter1"></a>
    </section>
    <section id="chapter2">
        <a id="chapter2"></a>
    </section>
    <section id="chapter3">
        <a id="chapter3"></a>
    </section>
</div>

Include the necessary JS code to enable the functionality:

$(".main").on("scroll",function(e){
    var fifty_percent_y = $(".main").height() * 0.5;
    var scroll_position = $(this).scrollTop();
    var prev_scroll_position = $(this).data('scroll_position');
    var delta = scroll_position - prev_scroll_position;
    $(this).data('scroll_position', scroll_position);


    //the rule is: if the top of chapter section tag crosses up across 50% then it becomes active, or if the bottom of a section tag crosses down across 50% then it becomes active.
    $('section').each(function(i, el){
        $this = $(this);
        var top_y = $this.position().top;
        var bottom_y = top_y + $this.height();
        if ((top_y     < fifty_percent_y && top_y    + delta > fifty_percent_y) ||
            (bottom_y  > fifty_percent_y && bottom_y + delta < fifty_percent_y)
           ){
            $("a").removeClass('active');
            $("a#" + $this[0].id).addClass('active');
            return false;
        }
    });
});

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

Chrome is experiencing compatibility issues with Datatable

I'm encountering an issue with Datatables and I'm at a loss on how to resolve it. In my custom cms, Datatables functions perfectly on my Mac (Safari, Chrome, Firefox) and also works seamlessly for my colleagues on Windows machines. However, we ...

Optimizing the Placement of Dynamic Google Maps

After setting up a responsive Google map using this jsFiddle and guidance from this stack overflow post, I encountered an issue. How can I keep the map centered on the marker across various viewports and browser sizes? I came across a solution in this res ...

Difficulties encountered when attempting to use a background image for shadow effects within a CSS design

I have been learning from a tutorial on how to create a fixed tabless CSS layout, starting from Photoshop and ending with HTML+CSS code. Here is the final example suggested by the tutorial (how it should look like in the end): And this is my own version ...

Utilizing single-use bindings for a unique element directive

I'm working on a new directive called <call-card> and I want to implement one-time bindings as an exercise for optimizing future directives. Here is the definition object for this directive: { restrict: 'E', controllerAs: &ap ...

Determine if a specific route path exists within the URL in Angular

http://localhost:4200/dsc-ui/#message but if I change the URL to (remove #message and type application-management) http://localhost:4200/dsc-ui/application-management (/application-management), it should automatically redirect me to http://localhost:4200/d ...

Repetition of UTM Parameters

I created a web page with a donation form embedded in it. Donors visiting the page come through a link that includes a source code at the end. I managed to include this source code in the URL of the embedded form using the following code: $(document).ready ...

The functionality of Express' render/redirect is limited to being triggered only by a submit method within a form

Objective To execute a POST request through a JavaScript method in order to send variable values as parameters. Setup NodeJS Express BodyParser ejs Initial Approach Frontend: <html> <head> <script src='http://ajax.go ...

CSS switch status toggle

Here's my code for a toggle switch from . I'm trying to change the label before the switch/checkbox to display "checked" or "not checked" based on the toggle state. When I click on the label, it changes the switch but not the text. JavaScript: ...

Error: Element table in VueJS contains a duplicate key

Here is the code snippet that I am working with: <el-table :data="getFormattedLocationTableData" style="width: 100%" :fit="true" rowKey="treeId" > <el-tabl ...

Introducing React JSX via a nifty bookmarklet

Looking to convert code found in an HTML file into a bookmarklet? Here's the code snippets involved: <script src="JSXTransformer-0.13.3.js"></script> <script src="react-0.13.3.js"></script> <script type="text/jsx;harmony=tr ...

Is your Jquery validation malfunctioning?

I am currently facing a challenge with required validation on an asp.net page. In order to validate the inputs, I have implemented multiple controls which can be hidden or displayed based on certain conditions. These controls include checkboxlists, dropdow ...

Is it possible to interact with Java SE jars using JavaScript?

I need to integrate an API that is written in Java with a Client written in JavaScript. Is there any way to use this API, possibly along with other Java-SE JARs, in Webstorm? Any assistance would be greatly appreciated. Thank you! ...

Having trouble linking the component to the Redux store

I've been encountering difficulties connecting my CMSForm component to the Redux store. Below are the snippets of code that I have implemented: Reducer: const cmsDefaultState = { cmsNum: "", facilityName: "" }; export default (state = cmsDefault ...

Striving to make edits that will reflect changes in the database, however, I continue to encounter error CS0123 stating that there is no matching overload for 'Insert_Click' with the delegate 'EventHandler'

Welcome to the front-end of my webpage: <div class="div"> <asp:Button style="background-color: #007aff; width: 100%; padding: 5px" Text="SAVE" OnClick="Insert_Click" ID="InsertID" runat="s ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

Separate Your Navbar with Bootstrap 4 Separators

I'm facing a challenge in adding separators within a navigation bar between the navigation items. I am unsure how to evenly space out the padding on these separators next to each navigation item. https://i.sstatic.net/vjYti.png Another issue I encou ...

How do I effectively replace content with a banner or alert message for users experiencing issues with the website on Internet Explorer?

mysite seems to be struggling with displaying 3D content on Internet Explorer compared to Chrome. Is there a way I can replace the content with a banner or alert informing users that they will have a better experience using Chrome or other supported browse ...

Android Chrome users experiencing sidebar disappearance after first toggle

Over the past few days, I've dedicated my time to developing a new project. I've been focusing on creating the HTML, CSS, and Java layout to ensure everything works seamlessly. After completing most of the work, the design looks great on desktop ...

Customizing App (directory) elements in next.js 13

Imagine having this directory organization: https://i.stack.imgur.com/Hd5gu.png Is there a method for loading the component from the custom folder instead of the default one in the app folder? In case the custom folder does not have that component, can t ...

Next.js page transitions causing Google Tag Manager to malfunction with 'react-gtm-module'

I am currently working on a Next.js project and have successfully integrated Google Tag Manager (GTM) using the react-gtm-module package. Interestingly, everything works perfectly when the application is initially loaded in debug mode, regardless of the st ...