I am trying to use jQuery to dynamically change classes based on certain conditions. However, I am encountering an issue where the class of my 'home' link remains unchanged even after clicking on another link. How

How can I modify my jQuery code to achieve the following:

If the 'home page' is active, then apply CSS class A (dark green color) to the 'home link'; otherwise, apply CSS class B (brown color).

(In essence, I want the relevant link to be dark green without a hover effect when on the current page, and for other links to be brown but turn light green when hovered over.)

The current code works perfectly as intended, except for one issue - when clicking on any link, the dark green color does not disappear from the 'home' link. This is due to the CSS rule: #menuDisplayedHome a { color: #568a38; /* Dark Green */ } .... Check it out here: https://jsfiddle.net/mhfn7kw0/2/embedded/result/ (Click on 'about' followed by 'home' to see the slider animation).

Note: all pages are within a jQuery slider, meaning that they are technically on the same page.

Here is the current code:

CSS:

#menuDisplayed a {
        text-decoration:none;
        color: #8F5C3E;    /* Brown */
        }

    #menuDisplayed a:not(.no-hover):hover {
        color:#6bab4a ;   /* Light Green */
        }

    #menuDisplayedHome a  {
        color: #568a38; /* Dark Green */
        }   

    #menuDisplayed a.no-hover {
        color: #568a38;       /* Dark Green */
        }

HTML:

<div id="wrapper">

    <div id="headingLogoBar">
        <div id="logoBarImageDiv">
            <img id="">
        </div>

        <div id="menuDisplayed">
                <ul>
                    <li id="menuDisplayedHome"><a href="#target1" class="forMovingPanel">HOME</li>
                    <li id="menuDisplayedAbout"><a href="#target2" class="forMovingPanel">ABOUT</a></li>        
                    <li id="menuDisplayedPortfolio"><a href="#target3" class="forMovingPanel">PORTFOLIO</a></li>    
                    <li id="menuDisplayedContact"><a href="#target4" class="forMovingPanel">CONTACT</a></li>
                </ul>
        </div>
    </div>

    <div class="forMovingPanel active" id="target1" style="left:0; display:block;">
        <h3 style="text-align:center">Home</h3>
    </div>


    <div class="forMovingPanel" id="target2">
            <h3 style="text-align:center">About</h3>
    </div>

    <div class="forMovingPanel" id="target3" >
        <h3 style="text-align:center">Portfolio</h3>
    </div>

    <div class="forMovingPanel" id="target4" >
        <h3 style="text-align:center">Contact</h3>
    </div>

</div>

jQuery for changing link colors:

<script>

$('#menuDisplayedHome a').on('click', function() {
    $(this).addClass('no-hover');
    $('#menuDisplayedContact a').removeClass('no-hover'); 
    $('#menuDisplayedPortfolio a').removeClass('no-hover'); 
    $('#menuDisplayedAbout a').removeClass('no-hover'); 
    });

$('#menuDisplayedAbout a').on('click', function() {
    $(this).addClass('no-hover');
    $('#menuDisplayedContact a').removeClass('no-hover'); 
    $('#menuDisplayedPortfolio a').removeClass('no-hover'); 
    $('#menuDisplayedHome a').removeClass('no-hover');
    $('#menuDisplayedHome a').addClass('menuDisplayed a');
    });

$('#menuDisplayedContact a').on('click', function() {
    $(this).addClass('no-hover');
    $('#menuDisplayedAbout a').removeClass('no-hover'); 
    $('#menuDisplayedPortfolio a').removeClass('no-hover'); 
    $('#menuDisplayedHome a').removeClass('no-hover'); 
    $('#menuDisplayedHome a').addClass('menuDisplayed a');
    });

$('#menuDisplayedPortfolio a').on('click', function() {
    $(this).addClass('no-hover');
    $('#menuDisplayedAbout a').removeClass('no-hover'); 
    $('#menuDisplayedContact a').removeClass('no-hover'); 
    $('#menuDisplayedHome a').removeClass('no-hover'); 
    $('#menuDisplayedHome a').addClass('menuDisplayed a');
    });

</script>

jQuery for the slider:

jQuery(function($) {

$('a.forMovingPanel').click(function() {
    var $target = $($(this).attr('href')),
        $other = $target.siblings('.active');

    if ($(".forMovingPanel").is(':animated')) return false;

    if (!$target.hasClass('active')) {
        $other.each(function(index, self) {
            var $this = $(this);
            $this.removeClass('active').animate({
                left: $this.width()
            }, 500);
        });

        $target.addClass('active').show().css({
            left: -($target.width())
        }).animate({
            left: 0
        }, 500);
    }
});

});

Answer №1

If I were to offer a suggestion, I'd recommend utilizing the .click() method instead of .on(). It seems that when using .on(), you need to begin with $(document) rather than the actual element intended for clicking. Then, include that element within the parameters.

Moreover, it appears that you are attempting to assign a class value of "menuDisplayed a". However, this is not a valid class as menuDisplayed was previously defined as an ID. If it were up to me, I would convert some IDs to classes and streamline the structure a bit; always bear in mind that IDs take precedence over classes.

In my view, it may be more efficient to allocate the same class to all your <a> tags (or omit the no-hover class altogether). Subsequently, once $(document) is .ready(), you can instruct jQuery to automatically set HOME to dark-green without requiring a click or alternative event, simply upon page completion of loading. A revised approach for handling classes in jQuery could look like:

$(document).ready(function(){
$('#menuDisplayedHome a').addClass('no-hover');

$('#menuDisplayedHome a').click(function() {      /* upon div click */
    $(this).addClass('no-hover');     /* apply 'no-hover' class = dark green */
    $('#menuDisplayedContact a').removeClass('no-hover'); 
    $('#menuDisplayedPortfolio a').removeClass('no-hover'); 
    $('#menuDisplayedAbout a').removeClass('no-hover'); 
    });

// Additional conversion functions go here

});

Regarding CSS enhancements, consider the following snippet:

.menuDisplayed a {
        text-decoration: none;
        color: #8F5C3E;    /* Brown */
        }

.menuDisplayed a:not(.no-hover):hover { /* hover styling exclusion for elements with 'no-hover' class */
        color: #6bab4a;   /* Light Green */
        }

.menuDisplayed a.no-hover  {
        color: #568a38; /* Dark Green */
        }

Answer №2

Upon initial reflection, the most straightforward solution that comes to mind is to incorporate the no-hover class into the homepage link.

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

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

Enhancing ajax requests with headers in Ember.js

My goal is to configure request headers for my emberjs application. However, when setting it up in the initializer, the client_id appears as [object Object] instead of the actual value. This is the initializer that runs when the application starts. Apikey ...

Conceal a div once the content in a separate div has finished loading

After loading an image in slices inside a div, I want to ensure that the entire content is loaded before displaying the div. To achieve this, I am using another div as a mask while the content loads: <div id="prepage" style="position:absolute; left:0px ...

Issue with customizing the appearance of the selected option in a dropdown menu

Is there a way to change the background color of each option in a select box when it is selected? Currently, when an option is clicked, it appears blue along with the selected text color. I have tried various selectors like :active, :focus, ::selection, [s ...

Accessing an element by its ID with the help of a looping

Looking to retrieve a string from my database and insert it into my paragraphs: <p id="q_1"></p> <p id="q_2"></p> The following code works correctly: $.get("bewertung/get/1", function (data) { document.getElementById("q_1") ...

Is misbehavior expected at approximately 600 pixels in width?

What is happening with my website when the width is minimized, and how can I resolve it? Issue The website appears fine on mobile devices and full screens, but at reduced sizes, the background image disappears and the top bar behaves strangely (with the l ...

As you hover over the div, the content inside subtly shifts upwards and downwards

I am facing an issue with my movie list. When hovering over a movie, a border appears around it as expected. However, I also notice that at the same time, it seems like extra padding is being added to the 'top' and 'bottom', causing the ...

The static files for the icon CSS (404 Error) from Flaticon and Font-mfizz are failing to load properly

When I was designing a website, I needed an icon of Python, so I turned to Flaticon and found what I was looking for. This snippet shows the HTML code I used: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <li ...

How can DataTables (JQuery) filter multiple columns using a text box with data stored in an array?

I've been attempting to create a multi-column filter similar to what's shown on this page () using an array containing all the data (referred to as 'my_array_data'). However, I'm facing issues with displaying those filter text boxe ...

What steps should be followed in order to integrate two themes within a single DOM element while utilizing a ThemeProvider?

<ThemeProvider theme={theme}> My goal is to utilize two themes simultaneously on a single DOM element using a theme provider. style={theme.flexRowLeft} Struggling with incorporating multiple themes at once, I am currently restricted to applying on ...

"Creating a dynamic loop in jQuery using JSON data fetched through an AJAX call to

I am a newcomer to Javascript and I am working on a jQuery-ajax-php project that seems to be exhibiting some strange behavior. The functionality works, but only sometimes. Here is my desired sequence of actions: Set up form settings (works) Retrieve JSO ...

Strategies for creating a dynamic progress bar using jQuery and JavaScript

I'm currently working on a project that involves increasing a percentage number while filling up the background color inside it based on the percentage value. The current setup is functional in terms of animating the background, but I need it to dynam ...

Is there a performance boost when using queue() and filter() together in jQuery?

I'm currently refactoring some Jquery code and I've heard that chaining can improve performance. Question: Does this also apply to chains involving queue() and filter()? For instance, here is the un-chained version: var self = this, co = ...

Is it necessary to include the jQuery-Do alert command before using console.log() in JavaScript or jQuery code?

const firstResponse = ""; $.get("firstCall.html", function (response) { processResponse(response); }); function processResponse(content) { firstResponse = content; } const secondResponse = ""; $.get("seco ...

Arranging two list items (<li>) side by side in HTML code

I am currently designing a form with a side navigation bar that will display around 15-20 elements. Each element is represented by an <li> containing a link to open a modal when clicked. This is the current structure of my code: <div id="sidebar ...

Creating a consistent height for Bootstrap 5 Carousel items with varying sizes

I am currently utilizing Bootstrap 5 carousel to display a collection of user-uploaded images that vary in height and width. I am seeking to create a carousel with responsive height and scaled/filled images. Below is the HTML + CSS code snippet I am using ...

Tips for resolving the final item issue in Owl Carousel when using right-to-left (RTL)

Encountering a bug with the rtl setting in owl-carousel. When the rtl is applied to the slider and I reach the last item, the entire slider disappears! Here's the code snippet: var viewportWidth = $("body").innerWidth(); if (viewportWidth & ...

A step-by-step guide on making an animation series with html and css keyframes

I've been working on creating a captivating animation using HTML and CSS keyframes, but I seem to have hit a roadblock. Despite trying different rotations and transforms, I can't seem to achieve the desired effect depicted in the image below. The ...

Is there a way to align this button perfectly with the textboxes?

https://i.sstatic.net/ODkgE.png Is there a way to align the left side of the button with the textboxes in my form? I'm using bootstrap 3 for this. Here is the HTML code for my form. I can provide the CSS if needed. Thanks. h1 { font-size:83px; ...

Having trouble with the initial tap not being recognized on your mobile browser?

When using mobile web browsers (specifically chrome and firefox on iOS), I am experiencing an issue where the hamburger menu does not trigger when tapped for the first time. For a simplified version of the HTML/CSS/JS code, you can check it out at: https ...