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

JavaScript Animation of Text

I have a challenge where I want to animate text's opacity in JavaScript after the user presses enter. However, I am struggling to achieve this with my current code. I can provide all of my code for you to review and help me understand why the animatio ...

Steps to customize the Spark theme in Flex 4

In the default Spark theme in Flex 4, what type of styling is included? Additionally, how can one override the Spark theme? For instance, when attempting to change the background color but seeing no effect, even though the CSS code appears correct. Here&ap ...

Struggling to make fadeIn() function properly in conjunction with addClass

I've been struggling with this issue for quite some time now and I just can't seem to make it work. The JavaScript I'm working on involves using addClass and removeClass to display and hide a submenu element. While the addclass and removeCla ...

I'm having trouble getting the npm install for classnames to work within my li tag

I need some help with React JS. I'm attempting to merge my classes using the npm package called classnames. https://www.npmjs.com/package/classnames However, I'm encountering an issue: classnames doesn't seem to be working as expecte ...

The concept of AJAX send function and toggling button visibility

I am facing a challenge with a textarea and send button on a panel that is displayed after entering the first character. The visibility of the button is controlled by the isButtonVisible() method. Once clicked, it sends the text from the textarea using the ...

Footer not positioned at the bottom of the page

I have been experimenting with different ways to keep my footer at the bottom of the page. Initially, I tried using position: static, but the footer ended up above the bottom of the page and the background was visible (similar to the image below). Then, I ...

Issue with iPad CSS floats causing layout problems?

Having a css challenge with the layout on ipad for this particular website: When viewing on a browser, the social media icons align correctly to the right. However, on an iPad or iPhone, they are not aligned all the way to the right. Is there anything tha ...

The importance of scope in ng-style

I am attempting to dynamically change the font color in an input field based on the value entered into that field. However, I have encountered an issue with using ng-style as it is not recognizing the value of the scope and therefore the color does not upd ...

Seeking an AJAX jQuery method for retrieving the values of four fields and transmitting them to the server

My MVC application is in need of extracting values from a variable number of field values, including: field_1, field_2 .. field_4 The goal is to send these values to the controller and update the text of a Div element based on the response. I have limit ...

resolving table refresh problem with the use of ajax, JQuery, and JSON

I have populated a set of records in HTML table format. Each row includes an anchor tag with a trash-can image at the last column. When this image is clicked, I want to delete the respective row and refresh the table with updated data. My approach involves ...

Scale first, then drag and drop to fix a faulty registration

I'm currently working on a project that involves dragging and dropping the correct items onto a technical drawing, such as a motherboard. The user is presented with pictures of components like CPUs or DDR memory and must drag these items to their corr ...

Navigating Liferay Portlet in reverse order

I am facing an issue with right to left alignment in my portlet. It displays correctly when tested on a regular HTML page, but switches to left to right alignment when integrated into a Liferay portlet. Below is the code snippet causing this problem: < ...

Adding negative values to the Tailwind CSS utility plugin is a simple process that can greatly enhance

Adding Negative Values to Tailwind CSS Utility Plugin Quick Summary: I've developed a custom Tailwind utility plugin that includes numeric values. I'm looking for a way to introduce negative numbers by adding a - at the start of the class, simi ...

Inability to load a MySQL table using Ajax on the same webpage

I'm facing an issue where I want to load a table from mySql on the same page without getting redirected to another page. The user selects a date range, and upon pressing submit, it should appear in the designated div id tag. However, the functionality ...

Display Image Automatically Upon Page Opening

Currently, I have an HTML file that includes the following code: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> I am attempting to retrieve the image from a file when the webpage loads using the server.js file ...

Adjust text alignment dynamically as a div changes size with CSS in ASP.NET

For the menu bar on my site, I utilized flex containers and nested div elements. Currently, all text is aligned at the center. However, when the website is viewed on smaller devices and it resizes, I would like the text to be aligned to the left. Is there ...

Merge web address when form is sent

I'm currently working on a search application using the Django framework and the Yelp API as my backend, which is functioning properly. However, I am facing some challenges with the frontend development, specifically integrating Leaflet.js. My search ...

JavaScript has encountered a syntax error

When working on an animation in javascript, I encountered a problem that I can't seem to identify. I am attempting to make the pan function work with the "mover" function, but it seems like either I am not using the properties correctly within the "tr ...

Divide a string into separate array items where a specific character is found

Within my sentence are several characters (~). I want to split the text before each ~ into an array item, and then add a <br /> tag at the end of each item. I attempted using the replace method but it only worked for the first ~ and disregarded the ...

Execute Javascript after modification of the DOM

I have developed two custom directives known as app-content and app-content-item. These directives are intended to be utilized in upcoming projects to provide a basic structure with simple styling. They will be incorporated into a module and should be nest ...