Create Better Divi Headers

How To Highlight Active Menu Items on Scroll in Divi

by | Apr 20, 2025 | 2 comments

If you’ve created a one-page Divi website with a fixed header, you’ve probably noticed a usability issue: as visitors scroll, the navigation menu doesn’t clearly indicate which section of the page they’re currently viewing. In this tutorial, I’ll show you how to highlight active menu items in Divi on scroll, providing clear visual feedback so your visitors always know exactly where they are on your page.

The method is straightforward and beginner-friendly—you can simply copy and paste the provided code directly into your website. Additionally, if you’re using Divi MadMenu, I’ll show you how to easily enable this functionality directly through its built-in settings with a single click. This feature is available for both for the MadMenu module and the MadMenu Vertical Menu module.

Table of Contents

Demo

Here’s a quick demo showing how menu items automatically become highlighted as you scroll up and down the page or click menu links to scroll directly to specific sections.

In this example, the active item’s text color turns red as soon as the corresponding section reaches the defined scroll position.

Highlighting Divi menu items on scroll demo

Benefits of Highlighting Active Menu Items on Scroll

Before jumping into the implementation, let’s quickly go over a few key benefits of highlighting active menu items on scroll for one-page designs:

  1. Better User Experience:
    By clearly indicating the current section, visitors always know exactly where they are on your page. This visual feedback provides intuitive navigation, making your website much easier and more pleasant to use.
  2. Improved Engagement:
    Highlighting active menu items encourages users to interact more naturally with your content, guiding them effortlessly from one section to another.

The idea behind this feature is straightforward: each menu item in your fixed navigation menu is linked to a specific section on the page, and, as users scroll or click through the menu links, the corresponding menu item dynamically becomes highlighted.

For example, imagine we have a simple navigation menu with four items: Home, Products, Blog, and Contact. Each menu item links to its own section on the page. When a user clicks on “Products” menu item, the page scrolls down smoothly to that section, and the “Products” menu item instantly becomes highlighted (active).

The same behavior occurs as the user scrolls manually through the page. As soon as a new section reaches the trigger point in the viewport, the corresponding menu item is highlighted automatically, clearly showing visitors their current position on the page.

Let’s now dive into how you can easily set up this effect on your Divi website.

Implementation

We’ll use JavaScript to detect scrolling and set the active menu item accordingly. Then we’ll highlight (style) this active menu item either via Divi Menu module’s built-in design settings or with custom CSS.

Here’s the step-by-step process we’ll follow:

  1. Create your Divi menu and page sections
    First, set up a fixed header in Divi Theme Builder containing menu items anchored directly to the sections of the page that you’ll assign this header to. Each menu link (like #products, #blog, etc.) will correspond to a specific section on the page.
  2. Manage the menu item’s active state
    We’ll then use JavaScript to dynamically detect which section of the page is currently in view. As users scroll, the JavaScript function automatically sets the appropriate menu item to active state.
  3. Style the active menu item
    Finally, we’ll visually highlight the active menu item using Menu module’s built-in design setting for changing the active link color, or by adding custom CSS for more flexibility.

Let’s go through these steps in detail.

Step 1. Prepare Your Divi Menu and Page Sections

First, we need to create a fixed header using the Divi Theme Builder. We won’t cover how to create a header template here since that’s beyond the scope of this tutorial. Just make sure your menu items link directly to specific page sections using anchor links (#), and ensure each corresponding section on the page has the matching CSS ID attribute.

For example, if you’d like the Products menu item to scroll to the Products section:

  1. Go to Appearance → Menus in your WordPress dashboard, select your desired menu, and add an anchor link (e.g., #products) into the URL field of the “Products” menu item:
Add anchor to menu item
  1. Next, edit the Products section on your Divi page. Open the Section Settings, then go to Advanced → CSS ID & Classes → CSS ID and enter the matching ID (in this example, products):
Add CSS ID to Divi section

Repeat these steps for all your other menu items and their matching sections.

Make your header fixed

For the active menu highlighting to be useful, the header needs to stay visible as users scroll down the page. Otherwise, users won’t see which menu item is highlighted.

To make your Divi header section fixed open the Section Settings → Advanced → Position and set the followings:

  1. Set the Position option to Fixed.
  2. Select the Top-Center location from the location picker.
Make Divi section fixed and select top-center location

Once you’ve done this, you’re ready to move on to the JavaScript setup.

Step 2. Manage the Menu Item’s Active State

The active state of the menu items is handled by the JavaScript code provided below.

/**
 * Highlights the currently viewed section's corresponding menu item on scroll.
 * 
 * Adds or removes the "current-menu-item" class on menu items based on the
 * scroll position relative to section elements on the page.
 *
 * @link https://divicio.us/tutorials/menu/how-to-highlight-active-menu-items-on-scroll-in-divi/
 *
 * @param {number}  [triggerOffset=200]     Vertical offset in pixels from the top
 *                                          of the viewport, determining when the
 *                                          highlighting is triggered. Default is 200.
 */
function dvcs_highlight_menu_items(triggerOffset = 200) {

    // Get all menu anchor items that need highlighting
    const menuItems = document.querySelectorAll(".et_pb_menu ul li a");

    // Get all sections present on the page
    const sections = document.querySelectorAll(".et_pb_section");

    // Variable to store ID of the currently active (viewed) section
    let activeSectionId = "";

    // Loop through each section to find the active one based on the scroll position
    sections.forEach(section => {
        const sectionTop = section.getBoundingClientRect().top;
        const sectionId = section.getAttribute("id");

        // If the top of the section is above the trigger offset, mark as active
        if (sectionTop < triggerOffset) {
            activeSectionId = sectionId;
        }
    });

    // Highlight the corresponding menu item by adding "current-menu-item" class
    menuItems.forEach(item => {
        const url = item.getAttribute("href");

        // Extract anchor ID from URL
        const anchorOnly = url.substring(url.indexOf('#') + 1).split('?')[0];

        if (anchorOnly === activeSectionId) {
            item.parentElement.classList.add("current-menu-item");
        } else {
            item.parentElement.classList.remove("current-menu-item");
        }
    });
}

/**
 * Throttle a function to limit its execution rate.
 *
 * This function ensures that the provided callback (`func`) is executed 
 * no more frequently than once every specified delay period (`delay`). 
 * It's useful for improving performance on frequent event listeners such as scrolling or resizing.
 *
 * @link https://divicio.us/tutorials/menu/how-to-highlight-active-menu-items-on-scroll-in-divi/
 *
 * @param   {Function}  func            The function to be throttled.
 * @param   {number}    [delay=100]     The minimum time interval in milliseconds between function calls.
 * @returns {Function}                  A throttled version of the input function.
 *
 */
function dvcs_throttle(func, delay = 100) {
    let timeoutId;

    return function(...args) {
        if (!timeoutId) {
            timeoutId = setTimeout(() => {
                func.apply(this, args);
                timeoutId = null;
            }, delay);
        }
    };
}

// Initialize highlighting functionality on page load and scroll
const dvcs_throttled_scroll_callback = dvcs_throttle(dvcs_highlight_menu_items, 100);

// Highlight correct item on page load
window.addEventListener("load", () => dvcs_highlight_menu_items(200));

// Update highlighting on scroll
document.addEventListener("scroll", () => dvcs_throttled_scroll_callback(200));

How it works

Here’s a quick breakdown of how this JavaScript snippet works behind the scenes:

  • The dvcs_highlight_menu_items() function tracks the vertical position of each section on the page relative to the viewport as you scroll.
  • Based on the provided triggerOffset (the threshold in pixels), the function determines which section is currently visible and should be considered “active”.
  • Once the active section is identified, the function assigns the current-menu-item CSS class to the corresponding menu item. This CSS class is used to highlight the active menu item visually.
  • Ensures optimal performance by utilizing the dvcs_throttle() function. It limits how frequently this scroll detection logic executes as you scroll through the page.

Why do we need throttling?

The purpose of the dvcs_throttle() function is to limit how frequently the dvcs_highlight_menu_items() function gets executed while the page is being scrolled. Throttling is especially useful for performance optimization when dealing with events that fire rapidly and continuously, such as scrolling or window resizing.

  • Scroll event:
    The browser fires scroll event continuously as users navigate up and down your page — it may fire as often as every pixel scrolled.
  • Resize event:
    Similarly, resizing the browser window also triggers numerous resize event fires in quick succession.

Without throttling, the dvcs_highlight_menu_items() function would run repeatedly at a very high frequency. Although it doesn’t perform particularly heavy calculations or DOM manipulations, these repeated executions could still lead to increased resource usage, possible UI lag, and reduced overall performance.

By applying throttling through the dvcs_throttle() function, we significantly limit how often the active menu item highlighting code runs. This keeps your site’s performance smooth, ensures responsive scrolling behavior, and provides a better browsing experience for your visitors.

Adding JavaScript

You can easily add this JavaScript to your Divi website in one of the following ways:

  • Code Module (Recommended):
    Add the JavaScript snippet directly into a Code module within your Divi header template. This approach ensures that the script loads only on pages where this specific header template is applied.
  • Divi Theme Options:
    Go to your WordPress dashboard → Divi → Theme Options → Integration → “Add code to the <body>” section, and paste the code there.
  • Child Theme JavaScript File:
    Paste the snippet into your child theme’s custom JavaScript file (if you’re using a child theme).

Choose whichever method best suits your setup, and you’re ready for the final step—styling your active menu items.

Step 3. Style the Active Menu Item

To visually highlight the active menu item you can set a different text color for it directly from the Divi Menu module settings. Navigate to Menu Settings → Design → Menu Text → Active Link Color and set your desired color there to distinguish the active menu items.

Set active link color in Divi Menu module settings

Currently, this is the only built-in styling option provided by Divi’s Menu module for active items.

If you’d like to apply more advanced styling, such as borders, backgrounds, etc., you’ll need to use custom CSS. Here’s a simple CSS snippet you can use as a starting point, which changes the font color but you can add additional CSS properties as needed:

/**
 * Style the active menu link
 */
.et_pb_menu ul li.current-menu-item > a {
    color: #E02B20 !important;
}

For example, you can try to implement the animated underline effect for active menu items.

Adding CSS

There are different ways to add this custom CSS to your site:

  1. For a specific header template:
    Add the CSS snippet directly into a Code module within your header template.
  2. Apply globally across your entire site:
    Paste the snippet into Divi → Theme Options → General → General → Custom CSS. Or add it to your child theme style.css file.
  3. Apply only to a specific Menu module:
    Open your Menu module settings, navigate to Advanced → Custom CSS → Module Elements → Active Menu Link, and paste the CSS snippet there:
Add the active menu link custom CSS in Divi Menu module settings

Choose the method best suited to your needs, save your changes, and the active menu link styling will take effect.

However, if your website uses caching (either through a plugin or server-side), you may need to clear your site cache and refresh your browser window to see the changes.

Enable Active Menu Item Highlighting in Divi MadMenu

If you’re using Divi MadMenu for creating your Divi site headers, enabling the active menu item highlighting on scroll requires just a single click.

This handy feature is available for both the Desktop Menu and Mobile Menu elements of the MadMenu module, as well as the MadMenu Vertical Menu module:

  • MadMenu Settings → Content → Desktop Menu → Highlight Items On Scroll
  • MadMenu Settings → Content → Mobile Menu → Highlight Items On Scroll
  • MadMenu Vertical Menu Settings → Content → Menu → Highlight Items On Scroll

Simply toggle the Highlight Items On Scroll option for each menu to enable automatic highlighting of active menu items on scroll:

Enable highlighting active menu items on scroll for Divi MadMenu menus

Wrapping Up

That’s it! You’ve learned how to highlight active menu items in Divi on scroll. This enhancement provides a more intuitive navigation experience, clearly guiding your visitors as they move through your site’s content.

We’ve covered how to prepare your page sections and menu anchors. Then we’ve set up the JavaScript to dynamically handle menu items active states, and applied highlighting of the active items using Divi Menu module‘s built-in design setting and custom CSS. Additionally, if you’re using Divi MadMenu, you’ve seen how effortlessly this feature can be enabled without touching any code.

Feel free to customize the provided CSS and JavaScript further to perfectly match your website’s needs. And don’t forget—if your changes don’t appear immediately, it’s most likely due to caching, so, simply clear all the cache and refresh the page.

View Live Demos & Get Divi MadMenu

    Download FREE Divi Sections

      2 Comments

      1. David Echavarria

        Thanks for share it. I will try it with a page with Bakery Menu.

        Reply
        • Ivan Chiurcci

          You’re welcome, David.

          Reply

      Submit a Comment

      Your email address will not be published. Required fields are marked *

      Get FREE Divi Layouts

      Download 20+ Divi templates for FREE!

      Please confirm your email address to complete your subscription. Thank you!

      Copy link