Element with adhesive properties alters its color at a particular location

I need the sticky element to change colors at specific points and then revert back to its original color. The color should be orange initially, green on block 2, and orange again on block 3. For the complete code and to address any issues with jQuery, please visit this link.

$(document).ready(function(){
/* Fixing the menu on scroll */
$('.header-menu-wrp')
    .addClass('original')
    .clone()
    .insertAfter('.header-menu-wrp')
    .addClass('cloned')
    .removeClass('original');

function resizeMenu(){
    var $original = $('.header-menu-wrp.original');
    var $cloned = $('.header-menu-wrp.cloned');
    
    if ($(window).scrollTop() >= ($original.offset().top)){    
        $cloned.css({
            'top': 0, 
            'width': $original.css('width'), 
            'display': 'block',
            'left': $original.offset().left+'px'
        });
        $original.css('visibility', 'hidden');
    } else {
        $cloned.css('display', 'none');
        $original.css('visibility', 'visible');
    }
}

$(window).scroll(function(){
    resizeMenu();
});

$(window).resize(function(){
    resizeMenu();   
});

/* Highlighting active menu items */
var last_id;
var $top_menu = $('.header-menu-wrp.cloned');
var menu_height = $top_menu.outerHeight(true);
var $menu_items = $top_menu.find('a');
var $scroll_items = $menu_items.map(function(){
    var item = $($(this).attr('href'));
    if (item.length){
        return item;
    }
});

$menu_items.click(function(e){
    var href = $(this).attr('href'),
    offset_top = href === '#' ? 0 : $(href).offset().top - menu_height;
    $('html, body').stop().animate({
        scrollTop: offset_top
    }, 300);
    e.preventDefault();
});

$(window).scroll(function(){
    var from_top = $(this).scrollTop() + menu_height;
    var mar = parseInt($top_menu.css('margin-bottom'));
    var cur = $scroll_items.map(function(){
        if ($(this).offset().top < from_top + mar){
            return this;
        }
    });
    cur = cur[cur.length - 1];
    var id = cur && cur.length ? cur[0].id : '';
    if (last_id !== id){
        last_id = id;
        $menu_items.parent()
            .removeClass('active')
            .end()
            .filter("[href='#" + id + "']")
            .parent()
            .addClass('active');
    }
});
});

Answer №1

To customize the appearance of each menu item and change colors accordingly, you can assign a specific color or flag to each element. Here's an example that demonstrates how to set the color green for the second menu block based on the 'menu-color' attribute. You can also define colors in the CSS and modify the menu styles by adjusting the class value in a similar manner.

Below is the HTML code:

<div class="header-menu-wrp">
    <div class="wrp">
        <div class="header-menu">
            <ul>
                <li><a href="#block-1">Block 1</a></li>
                <li menu-color="green"><a href="#block-2">Block 2</a></li>
                <li><a href="#block-3">Block 3</a></li>
                <li><a href="#block-4">Block 4</a></li>
            </ul>
        </div>
    </div>
</div>

And here is the corresponding Javascript code:

$(window).scroll(function(){
        var from_top = $(this).scrollTop() + menu_height;
        var mar = parseInt($top_menu.css('margin-bottom'));
        var cur = $scroll_items.map(function(){
            if ($(this).offset().top < from_top + mar){
                return this;
            }
        });
        cur = cur[cur.length - 1];
        var id = cur && cur.length ? cur[0].id : '';
        if (last_id !== id){
            last_id = id;

            // Select the menu block element
            let adjustedEl = $menu_items.parent()
                .removeClass('active')
                .end()
                .filter("[href='#" + id + "']")
                .parent()
                .addClass('active');
        
            let setColor = '';
            // Set the menu color based on the 'menu-color' attribute of the adjustedEl
            if (adjustedEl.attr('menu-color'))
                    setColor = adjustedEl.attr('menu-color');
        
            adjustedEl.closest('.header-menu-wrp').css('background-color', setColor);
         }
    });

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

When the Component is mounted, it triggers a GET request and passes the response as a prop to the child component. What occurs if I enter a URL that directly accesses the child

Consider a scenario where there are 2 URLs: website.com/Overview website.com/Overview/City When website.com/Overview is accessed, the component shown is Overview, while accessing website.com/Overview/City reveals the City component. An issue arises when ...

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

Using Node.js to send a photo through a Telegram Bot

I've been trying to send a photo via node.js using this function, but it's not working. telegram-bot-api https://www.npmjs.com/package/telegram-bot-api var telegram = require('telegram-bot-api'); var api = new telegram({ token: & ...

What is the process for accessing the data attributes of div elements and then transferring them to a cookie?

Although this question may have been answered before, I couldn't find a specific solution. Imagine I have the following div elements... <div class="listings-area"> <div itemtype="http://schema.org/Product" itemscope=""> <a class="lis ...

Is there anything amiss with this Ajax function invocation?

Here is the JavaScript code: $(document).ready(function() { $("#quantity").change(function() { hash = $("#quantity").val(); //returns 0001 (ex) qPrice_price = ajaxCall(hash); alert(qPrice_price); }); }); function aj ...

Oops! Module './api/routers' not found

Hello, I hope everyone is doing well... Currently, I am working on developing a NextJS single-page web application. To create a custom server for NextJs, I am utilizing Express, MongoDB, and nodemon for hot reload functionality. Upon starting the server, ...

Warning of superfluous escape character when executing 'npm start' on a React application

I have encountered a warning while running my React app using npm start. The warning appears in the terminal and reads as follows: Line 24: Unnecessary escape character: \[no-useless-escape The warning is related to the following code snippet: va ...

Exploring Tabletop.js to retrieve information from an array of data

Issue I am currently attempting to retrieve data from an array that contains two objects. I have implemented Tabletop.js to fetch the data from a public Google Spreadsheet, but I encountered an error in the console stating ReferenceError: object is not de ...

Using the max-width property with Semantic UI Dropdown in ReactJS

I'm struggling to determine how to adjust the max-width of the Dropdown element in ReactJS. I attempted the following: .Menu Dropdown { max-width: 5rem !important; } Unfortunately, this did not work as expected. The dropdowns are taking up too m ...

The trio of Angular, jQuery, and Chrome extensions is a powerful

I'm currently working on developing a Chrome extension that can alter the content of a specific website. However, since I don't have access to the source code of the website, I need to make these modifications using JavaScript. The goal is to ma ...

Double-clicking with Ajax and JSF after the initial click

When I interact with a dataTable that has a column named DELETE (which is a link) and has a listener attached to it, I experience an issue. After clicking on the link for the first time (click 1), the row gets deleted as expected. However, subsequent click ...

What is the method for eliminating PHP $_SESSION using AJAX?

I am facing an issue with removing an array within a PHP Session variable using AJAX. Here is the process I follow: HTML: <a href="#" onclick="delete_pix(false, '1', false, '1.jpg');">remove</a> JavaScript: functio ...

Tips for creating a responsive floating page div

Hey there, I'm still fairly new to web development and have a question regarding a registration page that is displayed as a floating div above the main page. How can I ensure that this div is centered in a responsive way? The pages are separated and ...

Exploring JQuery Mobile: A guide on looping through elements in a list and collecting their unique identifiers

I am facing a challenge with a list of li tags within an unordered list. Each tag is assigned a class=listitem and a data-clicked=true/false. My task is to extract only the id's of those with data-clicked=true, add them to a string named custidlist, a ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

Retrieve all the records from the collection that have a specific reference number in their ID field

Is it feasible to pull together all documents with an ID that includes a specific value? I am working with Angular 7. I attempted using db.collection('items').where.. but unfortunately, this method is not supported. For instance: (collection) ...

Reading a Json file with keys in puppeteer BDD: A Guide

Greetings, I am new to the world of puppeteer. I have successfully created my basic framework and now I am trying to figure out how to read data from .json files. I attempted to use the readFile method in my helper class, but unfortunately, it resulted in ...

leveraging array elements in the data and label properties of a chart.js chart

I would like to assign the values of an array to the data and label fields within a chart.js dataset. Below is the code executed upon successfully fetching JSON data using an AJAX call. The fetched JSON data is then stored in an array. Data = jQuery.pars ...

Enhanced by JQuery: Selecting items in a CheckBoxList

Is there a way to use jQuery on the client side to check a specific item in a CheckBoxList within a user control? <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AppCon %>" SelectCommand ...

Is it possible to assign a specific value to a row within a table?

For each row (tr) generated from my database, I would like to assign a unique row value. Let's consider the table being created: while ($row = $database->fetch_array($result)) { $i=1-$i; $class = "row".$i; echo "<tr class='{$class} produ ...