When an element possesses a particular class, modify the css styling of a different

My menu is an unordered list, with each menu item gaining the "active" class when clicked. This works perfectly fine. However, I have an arrow positioned absolutely and its "top" style needs to change based on which list item has the "active" class. Currently, it only checks during the initial site load and does not update when a different list item becomes active. Please note: The ".active-item" represents the arrow.


$(document).ready(function() {

    $('.nav .nav-items li').click(function () {
        $('.nav .nav-items li').removeClass('active');
        $(this).addClass('active');
    });

});

if ($('.nav .nav-items .nav-dash').hasClass('active')) {
    $('.nav .nav-items .active-item').css('top', '30px');
};

if ($('.nav .nav-items .nav-sales').hasClass('active')) {
    $('.nav .nav-items .active-item').css('top', '90px');
}; etc...

Answer №1

For the arrow positioning code to update on every click rather than just during page load, make sure it is placed within the click() handler for the menu item click event.

Answer №2

One effective way to achieve this would be through your stylesheet for improved performance:

.nav-items > .active .active-item{
    top: 0px;
}
.nav-items > .active.nav-sales .active-item{
    top: 30px;
}
.nav-items > .active.nav-sales .active-item{
    top: 90px;
} 
/* etc */

By utilizing CSS, you can reduce the amount of code required significantly.

In cases where it is absolutely necessary to implement this in JavaScript, the following approach should fulfill your requirements:

$(document).ready(function() {
    function checkNavItems(){
        if ($('.nav .nav-items .nav-dash').hasClass('active')) {
            $('.nav .nav-items .active-item').removeAttr('style');
            $('.nav .nav-items .active-item').css('top', '30px');
        };

        if ($('.nav .nav-items .nav-sales').hasClass('active')) {
            $('.nav .nav-items .active-item').removeAttr('style');
            $('.nav .nav-items .active-item').css('top', '90px');
        }; etc...
    }

    $('.nav .nav-items li').click(function () {
        $('.nav .nav-items li').removeClass('active');
        $(this).addClass('active');
        checkNavItems();
    });

    checkNavItems(); 
});

On closer inspection, your current code may not be achieving the desired result as intended. Specifically, you are clearing and setting styles for all active-item nodes instead of individual ones. While CSS is preferable for such tasks, below is a modified JavaScript solution that may help:

$(document).ready(function() {
    var activeStyles ={
        'nav-dash': {
            'top': '30px'
        }, 
        'nav-sales': {
            'top' : '90px'
        }
        //ETC
    } 

    function checkNavItems(){
        var active = $('.nav .nav-items .active'),
            activeItem = $('.nav .nav-items .active .active-item');
            inactiveItem = $('.nav .nav-items .not(.active) .active-item');
        activeItem.removeAttr('style');

        for (key in activeStyles) {
            if (activeStyles.hasOwnProperty(key) && active.hasClass(key)) {
                activeItem.css(activeStyles[key]);
                break; //Only do it once
            };
        };
    }

    $('.nav .nav-items li').click(function () {
        $('.nav .nav-items li').removeClass('active');
        $(this).addClass('active');
        checkNavItems();
    });

    checkNavItems(); 
});

For testing purposes, having access to example markup would facilitate the process. Please note that there might be some syntax errors present. However, the concept remains unchanged.

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

Troubleshooting issue with JQuery AJAX loading Bootstrap Dropdowns

I have a website on GitHub Pages that uses Bootstrap, but I'm having issues with the drop-down menu in the navbar. Sometimes it works and sometimes it doesn't. I am using $("#nav").load("url"); to load the navbar so that I can make changes and ha ...

The download attribute in HTML5 seems to be malfunctioning when encountering a 301 Moved Permanently

I am attempting to create an automatic download feature for a file from a URL with a 301 Moved Permanently redirection. Here is the current code: <a href="myserverapi/download?fileId=123" download="image.jpg" target="_blank" ...

Tips on choosing a button and applying custom styles with emotion styles in MUI

Looking to apply a margin-right to my button. Currently utilizing mui 5 with Button variant='contained'. I created a custom CSS style using the styled component in mui and targeted the Box. const Wrapper = styled(Box)({ display: 'flex&ap ...

Verify the presence of a particular attribute in an HTML tag using Capybara and polling techniques

In my HTML code, the attributes of buttons (such as "AAAAA") will change based on external events. This real-time update is achieved through AJAX pooling. <div class="parent"> <div class="group"><button title="AAAAA"/></div> <di ...

Navigation menu that is vertical and includes submenus, where the parent list item remains active even when visiting subpages

I'm currently utilizing Jekyll and Compass to construct an interactive prototype. Within one of my includes, I've implemented a sidebar navigation. The challenge arises when dealing with submenu items, as the active class on the parent (li) does ...

A guide on retrieving real-time data from PHP using Ajax

Being new to Ajax, I am struggling to grasp how to retrieve changing variable values from php. Below is the code snippet that I have been working on: <?php $pfstatetext = get_mypfstate(); $cpuusage= cpu_usage(); ?> <div id="show"> <c ...

What did I overlook in my AJAX implementation?

When a user selects a value from the dropdown menu, an Ajax call must be made to the server to retrieve some values in JSON format. Below is the Ajax code //AJAX Security $('#ddlSecurityLevel').change(function () { if ($('#ddlSecurityL ...

CSS font-face is not functioning as expected

I'm experiencing issues with importing a CSS font, and I'm puzzled as to why it's not working. The specific font in question is 'deadjim.ttf' and it is located within my main public_html directory. I have confirmed that the file p ...

Receiving an error message stating "The JSON value could not be converted to System.Int32" when attempting to post JSON data via AJAX to a Web API

I need to transfer information from my website to a WEB API that my partners are developing via AJAX. This WEB API is built on a .net Core 3.0 application, and the purpose is to register new users. However, I am encountering an issue with parsing the inpu ...

The resizing of the window does not trigger any changes in the jQuery functions

Here is a snippet of jQuery code that executes one function when the window size is large (>=1024) and another when it is resized to be small. Although the console.logs behave as expected on resize, the functions themselves do not change. This means that ...

What is the most effective method to override parent styles while utilizing CSS Modules?

I'm currently using NextJS along with CSS Modules for styling purposes. One of my goals is to adjust the appearance of a component in different scenarios: When it's rendered normally on a page, utilizing props to specify className modifiers. W ...

Sorting functionality in Dyntable is not functioning properly when called from an Ajax request

I can't seem to get DynaTable with Ajax to work properly. Sorting, searching, and pagination are not functioning as expected. When I click on the column header, nothing changes in my table. Could someone please assist me? Below is my code snippet: H ...

Function in head not triggering on OnMouseOver event

My goal is to have specific text display on my page when a user hovers over an image, with the text changing for each image. Below is the code snippet for the header section: <head> <title>Indian Spices Page</title> <link rel="s ...

Mobile FPS suffering due to slide-out drawer performance issues

My application features a drawer menu that functions smoothly on desktop, but experiences issues on mobile devices with noticeable lag. Within the header, I have implemented a boolean value that toggles between true and false upon clicking the hamburger i ...

Having trouble converting my form data into an array for table display

My website has a form for entering dummy patient information, with a table to display the submitted data. However, I'm facing an issue where the data is not being stored in the array when the user clicks the "Add Patient" button. Upon checking the arr ...

Inserting an item into a list

Looking for assistance with this particular scenario: { "EekvB3cnwEzE":{ "name":"hi", }, "Brv1R4C6bZnD":{ "name":"yup", }, "kRwRXju6ALJZ":{ "name":"okay", } } I'm attempting to store each of these objects in an array. Howe ...

Data is not being fetched by Ajax at regular 5-second intervals

How can I retrieve data every 5 seconds? I'm encountering an issue where it's not functioning as expected. This is the code I have, but it doesn't seem to be working: <script type="text/javascript"> $(document).ready(functio ...

Struggling to animate the selector of a nested div in Jquery?

Despite trying numerous variations, I am struggling to identify the correct selector of a nested div. The goal is to animate this particular div, but since no animations are taking place, I suspect that I have not selected the right element. Here is the a ...

Most efficient method to upload numerous images without any lag

I have a website where images are loaded only when they are slightly below the viewport. This method allows the site to load initially without images and then determine which ones need to be loaded based on the user's viewpoint. When a user scrolls ...

What is the process for updating a collection in MongoDB database with PHP?

After writing a code snippet to gather user input through a form and update a collection based on the entered product ID, I am encountering issues with incorrect results. It seems that I am unable to fetch the correct product ID value, which is causing t ...