Using jQuery to highlight the navigation menu when a specific div scrolls into view

I have implemented a side navigation consisting of circular divs. Clicking on one scrolls you to the corresponding .block div, and everything functions correctly. However, I am now curious if it is feasible to highlight the relevant .nav-item div based on which .block div is currently in view.
For example, if #block-3 becomes visible, the appropriate .nav-item div with data-hook="3" will be highlighted with a background-color: blue.

Check out the jsFiddle demo here: http://jsfiddle.net/rf4Ea/3/

HTML:

<div id="block-one" class="block"></div>
<div id="block-two" class="block"></div>
<div id="block-three" class="block"></div>
<div id="block-four" class="block"></div>
<div id="block-five" class="block"></div>

<ul class="nav-wrap">
    <li class="nav-item" data-hook="one"></li>
    <li class="nav-item" data-hook="two"></li>
    <li class="nav-item" data-hook="three"></li>
    <li class="nav-item" data-hook="four"></li>
    <li class="nav-item" data-hook="five"></li>
</ul>

jQuery:

$(document).ready(function () {

    Resize();
});

//Every resize of window
$(window).resize(function () {
    Resize();
});

//Dynamically assign height
function Resize() {
    // Handler for .ready() called.
    var divwid = $(window).height() / 2,
        navhei = $('.nav-wrap').height() / 2,
        newhei = divwid - navhei;
    $('.nav-wrap').css({
        'top': newhei
    });

}


$('.nav-item').click(function () {
    $('html, body').animate({
        scrollTop: $('#block-' + $(this).attr('data-hook')).offset().top - 0
    }, "slow");
});

If anyone has any suggestions on how to achieve this effect, your input would be greatly appreciated!

Answer №1

To make a selected class in your CSS and apply it like this:

.menu-link:hover, .menu-link.selected {
     background-color: green;
}

You can create a function that changes the color of the current menu item when scrolling:

function changeCurrentItemColor() {
    var height = $(".section:first").height();
    var currentIndex = Math.floor($(window).scrollTop() / height);
    var $currentMenuItem = $(".menu-link").eq(currentIndex);
    if (!$currentMenuItem.hasClass("selected")) {
        $(".selected").removeClass("selected");
        $currentMenuItem.addClass("selected");
    }    
}
changeCurrentItemColor();

$(window).scroll(function(event) {
    changeCurrentItemColor()
});

Check out the example on JsFiddle

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

Instructions on how to navigate back one page to determine which page initiated the action

I am looking for a solution to implement a back button that takes me back one page while caching it. Currently, I am using the following code: <a id="go-back" href="javascript:history.go(-1)" type="button" class="btn btn-danger">Back</a> Howe ...

Unable to execute JS script to navigate back to prior page with webdriver

Here is my code snippet: JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.history.go(-1);"); The code above isn't working. I've tried casting the webdriver instance but it doesn't work every time. I prefer not ...

Encountering a surprise Illegal Token JS Error

I am encountering a persistent "Unexpected Token ILLEGAL" error while attempting to run the script on the page after it has been registered. StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript&apos ...

Utilize CSS in your HTML using Express framework

I am attempting to link a css stylesheet to my basic html webpage. I am utilizing parse.com hosting for dynamic webpages that utilize express. There are numerous responses to this question, but none of them have proven successful in my case. I am trying ...

When using Ajax/PHP, the .post and .load methods do not yield any data in return

I've been working on an AJAX login/logout form, and while the login process is smooth, I'm encountering some issues with the "logout" functionality. Here's the Javascript code: $("#logout").live("click", function(){ $.post("/hd/ajax.php" ...

Refresh the main view in MVC from a partial view

I am currently working on an application following the MVC architecture. Within my project, I have a Parent View that incorporates a Partial View. The Partial View contains a submit function that triggers a Controller Method. In case of any errors, I nee ...

Sending Data to a PHP Script

I attempted to use the code below to send values to another PHP page but I am not receiving any output. File: Send.html <form id="form1" action="get.php" method="get"> <input name="search_name" type="text" id="search_name" size="20.5" height="45 ...

refresh jQuery following submission of ajax form

I currently have functioning jQuery code on my website. (function ($) { $(document).ready(function(){ if (!$('.normal').length) { $('#special').addClass("yellowstone"); } }); }(jQuery)); The "normal" selector is only loaded w ...

Tips for creating multiple full-screen overlays in HTML

I am new to the world of web development and I am currently working on implementing a set of buttons that will trigger specific overlays when clicked. I found the following code snippet on W3schools which creates a button along with an overlay effect. < ...

Exploring Laravel's method for retrieving data from multiple tables in the controller

In an effort to make my jQuery call more dynamic, I have a controller with the following method: public function api(Request $request , $project_id){ return Program::where('project_id',$project_id)->get(); } This results in: [{"id":178," ...

What is the best way to create a function that triggers another function every minute?

Currently, I have a function that checks if a user is authenticated: isAuthenticated = (): boolean => { xxx }; I am working with AngularJS and I want to create a new function called keepCheckingAuthentication() This new function should call the ...

The Firestore query for viewing resources is currently not functioning as expected due to issues with

I'm currently working on implementing the "read" Rules from an array, following the guidelines in this blog post var db = firebase.firestore(); db.collection("_users").where("viewers", "array-contains", myUID) .get() .then((querySnapshot ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Unable to assign default value to input field of type "time" in Chrome browser

I'm intrigued by Chrome's feature that automatically applies masking/formatting when using the type="time" attribute/value. However, I'm having trouble setting an initial value for the control. For example: <input type="ti ...

Issue with Next-Auth getServerSession failing to fetch user data in Nextjs 13.4 API Route

Having an issue with accessing user session data in a Next-Auth/Nextjs 13.4 API Route. I've set up the JWT and Session callback, but the user data defined in the callback function isn't translating correctly to what getServerSession is fetching i ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

Share a Node.js Express.js npm package for universal access within the project

Here is my current folder structure. /app.js /src /routes /controllers Within the routes folder, there are multiple javascript files that all require the passport.js package like so: const passport = require('passport'); Is it possible to c ...

What is the best way to incorporate markers into my d3 line chart that includes two separate datasets?

In my JavaScript code, I'm creating a line chart for two datasets using the d3 library with Vue framework integration. Within the HTML code, there are buttons that trigger the updateData function to display the line charts for the respective datasets ...

Unusual sidebar scrolling issues experienced in Firefox

Currently, I am in the process of developing an app with a scrolling sidebar. However, there seems to be some unexpected behavior when using Firefox: the content within the sidebar disappears partially below the top of the div if the mouse is positioned lo ...

When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project: wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' ))); As part of testing, I used an $http. ...