Changing CSS attributes with jQuery when conditions are met

After creating menus with expandable items that change style upon clicking, I encountered an issue where the styling changes were not being applied correctly.

To address this problem, I followed Sushanth's suggestion and replaced $this with $(this), but the issue still persisted. You can view the updated example below:

Code:

<script type='text/javascript'>
$(window).load(function(){
$(document).ready(function() {

    $(".toggle-trigger").click(function() {
        $(this).parent().nextAll('.toggle-wrap').first().slideToggle('slow','swing'); 


      if( $(this).is("menu2 .headline a")) {
            $(this).toggle(
                function(){
                $(this).parent().css("background-color","rgba(0, 0, 0, 0.1)",'border', 'solid 2px #009e0f');
                $(this).css("color","#009e0f");
                },
                function(){
                $(this).parent().css("background-color","#009e0f","border",'solid 2px #009e0f');
                $(this).css("color","#ffffff");
                }
            );
        }

        else if( $(this).is("#menu3 .headline a")) {
            $(this).toggle(
                function(){
                $(this).parent().css("background-color","rgba(0, 0, 0, 0.1)",'border', 'solid 2px #f7b50c');
                $(this).css("color","#f7b50c");
                },
                function(){
                $(this).parent().css("background-color","#009e0f","border",'solid 2px #f7b50c');
                $(this).css("color","#ffffff");
                }
            );
        }



    });
});

});

Answer №1

$this

meant to be //

In the if statements if( $this.is("menu2 .headline a"))

$(this)

Alternatively, use cached var $this = $(this)

MODIFY

I notice two additional issues with the code ...

  • Lacking # symbol in this line

    if( $(this).is("#menu2 .headline a"))
    The second problem lies in how you are setting the CSS properties..

    .css("background-color","#009e0f","border",'solid 2px #f7b50c')

You have multiple properties .. Ensure the properties are structured as a a map with key:value pairs..

.css({
       "background-color": "#009e0f",
       "border": 'solid 2px #f7b50c'
 });

View Fiddle

No need to wrap your code in both $(window).load() and DOM Ready handler.. One is enough. Additionally, there appears to be an issue with the toggling

MODIFY

Enhanced without utilizing toggle

$(document).ready(function() {
    $(".toggle-trigger").click(function() {
        // cache the div next to anchor
        var $div = $(this).parent().nextAll('.toggle-wrap').first();
        $div.slideToggle('slow', 'swing');
        // cache $(this)
        var $this = $(this);
        var background = '';
        var color = '';
        // Checking id the div has no class called hidden
        if (!$div.hasClass('hidden')) {
            // then add the class to the div
            $div.addClass('hidden');
            background = "rgba(0, 0, 0, 0.1)";
            // closest ancestor of the link clicked is menu2
            if ($this.closest('#menu2').length) {
                color = "#009e0f";
            }
            // closest ancestor of the link clicked is menu2
            else if ($this.closest('#menu3').length) {
                color = "#f7b50c";
            }
        }
        // if the div has a class hidden then 
        else {
            // Remove the hidden class
            $div.removeClass('hidden');
            color = "#ffffff";
            if ($this.closest('#menu2').length) {
                background = "#009e0f";
            }
            else if ($this.closest('#menu3').length) {
                background = "#f7b50c";
            }
        }
        // set the background  and color based on conditions
        $this.parent().css("background-color" , background );
        $this.css("color" , color);
    });
});​

Improved Fiddle

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

Unnecessary list elements generated by dazzling navbarPage

While developing an app with shiny using navbarPage, I noticed that there are some unwanted li tags in the HTML that are not defined in my code. Could this be a known bug? How can I go about fixing it? <nav class="navbar navbar-default navbar-stati ...

Why have the bars been positioned on the left instead of the right, and why does the mobile version require sliding instead of simply accessing the menu through a function?

Hello everyone, I'm currently working on designing a mobile-friendly header menu with the bars positioned on the right side of the screen. The goal is to utilize JavaScript to allow users to click either an 'X' icon or the bars to open the m ...

Moving Text Over a Static Background Image in HTML and CSS

Currently working on developing a website that involves coding in HTML and CSS. However, I've encountered an issue while programming. Whenever I attempt to adjust the positioning of my text, the background image shifts along with it, making it impossi ...

Avoiding the use of apostrophes in jQuery or JavaScript

I need to show the text below for the <span> element. What's the best way to handle single quotes in this case? $("#spn_err").text($('#txt1').attr('value')+" is not valid"); The desired message format is 'ZZZ' is ...

Make the background disappear when the text field is left empty and the cursor is not present (onUnfocus)

When the text field is empty and there is no cursor in the text field, I want it to be transparent and for the spell checker not working. The result should be displayed a little to the left inside a <div>. Should this be done using CSS, JavaScript, ...

Tips for creating a "sticky" button in Angular that reveals a menu when clicked

Is there a way to incorporate a feature similar to the "Get help" button on this website: The button, located in the lower right corner, opens a sticky chat menu. I am interested in adding dynamic information to the button (such as the number of tasks a u ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

Accessing HP ALM with REST and JavaScript on a local server: A step-by-step guide

I am trying to access ALM using locally written JavaScript in the browser (IE11, Firefox) through the REST API, but I am unable to login. Below is the code snippet where I am attempting to request the LWSSO cookie with jQuery: var auth = btoa(USER+":"+PAS ...

Exploring the height and overflow properties of nested div elements

Imagine a scenario where you have a fixed-size container and need all the elements to fit inside. The issue arises when some elements contain lots of text, causing the overflow to be hidden but still stretching beyond the container's height. How can t ...

Tips for centering a flexbox on a webpage:

<template> <div> <div class="flex justify-center w-full"> <div class="h-px-500 md:w-1/6 bg-orange-200 text-center">1</div> <div class="h-px-500 md:w-1/6 bg-orange-300 text-center">2</div> <div clas ...

What if the targeted URL is unresponsive and not returning any results?

Here is an example of the code I'm using to send a request to a URL at a fixed time interval. $(document).ready(function() { var counter = 1; $.doTimeout( 1000, function() { $.ajax({ type: "GET", url: "<%=e ...

Tips for sending multiple HTTP requests to a single page from a single client

Is there a way to run multiple AJAX calls on the same page from the same client without them getting queued by the server? The calls are starting correctly, but it seems like the server is executing only one request at a time. I've checked the start ...

comparing caching with jquery deferred against promise

Currently, I have implemented code using jQuery Deferred and ajax to fetch data from a remote API, store it in localStorage, and retrieve it from there. However, this code has a bug where it doesn't display the data properly the first time it runs (re ...

Guide: Extracting a targeted input field value from an external webpage with Javascript

After successfully retrieving the webpage content from an external website using ajax, my next goal is to develop a function that can extract a specific input field value which is already pre-filled. The structure of the webpage content looks something li ...

Adjust the cell text overflow based on the width of the table

I am working with a table that has multiple columns. I want the first 3 columns to have a larger width than the others, specifically taking up 15% each for a total of 45% of the table's width. Currently, I am using this code in a sandbox environment: ...

Tips for placing an icon within an input field

I'm struggling to place an icon inside an input tag, but it always appears at the bottom of the input. I initially tried using Bootstrap, but I ended up resorting to custom styles for this specific issue. Here's the HTML code: <d ...

Ways to animate elements while scrolling in React.js?

I am new to using React.JS and currently working on setting up an E-commerce Store. My goal is to have 5 images stack on top of each other and move together as the user scrolls. I used to achieve this effect in Vanilla JavaScript by adding a window.addEven ...

Unable to add items to the global JavaScript array variable

My goal is to populate a global array variable within my ready function, but when I attempt to access the data later on, the array appears to be empty. This is how my ready function looks: var counter = 0; var services = []; var names = [] va ...

Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example: <div [style.background-image]="profileImage" ></div> In the TypeScript file: We declare private profileImage: any; and use DomSanitizer for security. Fetching photo from service: We set this.profileImage using b ...

javascript functions failing to execute once the page has finished loading

I am new to front-end development and I've started using AngularJs for my project. I have set up routes and controllers within a module, which are then referenced in the HTML page. The controller's task is to display a carousel inside an ng-view ...