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

Customize PrimeNG component styles

Utilizing the PrimeNG OverlayPanel for a dropdown click feature, I am encountering an issue with moving the default left arrow to the right position. Despite trying various solutions, I have reached a dead end. Would you be able to provide me with some fr ...

Creating a tree with branches using divs: a comprehensive guide

I have been tasked with designing a tree structure for a project that will visually represent the results of a quiz. The tree needs to have branches on both sides, featuring 4 main branches, each with 5 smaller branches extending from them. Additionally, I ...

Struggling to deploy my Asp.Net Core + Angular application on Azure platform

I have developed an asp.net core application with angular2 on the front end using dotnet new angular. However, upon trying to publish it to the server, I encountered issues with installing dependencies: npm install npm ERR! Windows_NT 10.0.14393 npm ERR! ...

UI-Select fails to display the already selected value

Does anyone have a solution for binding a UI-Select control to a Class[] list? The filling up part works fine, but I'm having trouble getting the selected item to display. Any suggestions on how to fix this? Below is my ui-select code: <ui-select ...

Leveraging the :checked state in CSS to trigger click actions

Is there a way to revert back to the unchecked or normal state when clicking elsewhere in the window, after using the :checked state to define the action for the clicked event? ...

Switch the dropdown selection depending on the checkbox status

I'm currently facing a bit of confusion with my project. I am constrained by an existing framework and need to come up with a workaround. To simplify, I am tasked with populating a dropdown list based on the selected checkboxes. I have managed to get ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

What is the reason for the additional line being generated?

Can anyone explain why there is an extra line being produced here? I came across another question where it was mentioned that this issue is not due to CSS but rather caused by HTML. Why is that? This is completely new to me, and I'm curious as to wh ...

What is causing these divs to shift apart instead of staying next to each other when the browser window is resized?

I am facing an issue with two of my divs not staying next to each other when resizing the browser window. They align perfectly when the window is wide, but as soon as I resize it to a narrower resolution, the right div moves below the left one: http://jsfi ...

Issue with tile size or alignment in Safari

Recently, while creating my portfolio on CodePen, everything was running smoothly except for one little hiccup - Safari. http://codepen.io/tpalmer75/pen/FijEh (SASS for just one .item element) .item width: calc(100% / 3) display: inline-block height ...

Ways to divide background color in half using CSS

Looking for some help with CSS - I want to split an HTML page into two sections, with a background and text/login form on top. Can anyone provide sample CSS and HTML code? This is what I've tried so far in CSS: .logindiv { height: 200px; width: ...

Adjust the spacing of a div based on the fluctuating height of another dynamically changing div

Is it possible to dynamically adjust the margin of a div using jQuery or JS? Currently, I have set a margin on a div by calculating the height of a container that includes images. var articleImageHeight = $('.slides_control').height(); $(' ...

Creating a progress bar that includes hyperlinks: A step-by-step guide

Currently, I am in the process of developing an application form that consists of 9 pages of questions. Initially, I had implemented a progress bar which indicated completion by filling up 1/9 for each page completed. However, I have been informed that thi ...

Changing colors when hovering over different elements

I am struggling to create a hover color change effect that applies to all elements (icon, text, and button) from top to bottom. Currently, the hover effect only changes the color of either the text and icon or the button individually. Below is the code sn ...

Using Selenium to locate and click on a hyperlink within a table by identifying it with its displayed name

In my case, I have a table that displays records of school districts. My goal is to use Selenium in order to select the delete icon positioned in the eighth td for the district located on a row with a specific name. In this scenario, the name being QA__run ...

Making use of JavaScript's XMLHttpRequest() function allows for seamless

My issue revolves around my use of multiple XMLHttpRequest() requests in order to retrieve the value (miniTable) returned by the TableRow() function. Strangely, while I get the desired value when using alert() at the end of the TableRow() function, the T ...

The jQuery Datetime Picker

I am currently attempting to utilize a date and time picker found at the following link: However, I am facing an issue where this picker only functions properly when the jquery-ui.js file is excluded. It seems that there may be a conflict with the base jq ...

What is the best way to incorporate two range sliders on a single webpage?

I recently started using rangeslider.js on my webpage. I wanted to convert two input fields into range sliders, so I began by converting one successfully. Initially, the HTML code looked like this: <div class="rangeslider-wrap"> <input type=" ...

Ways to Press the Enter Key on Different Browsers

Looking for a solution to get the keypress action working properly? I have a chat feature where I need to send messages. Here is what I have in the Form-tag (JSP based): function SendMessage() { if (event.keyCode===13) { ale ...

Although JQuery is able to remove a row from the page, the record in the database is not

I'm having some trouble using jQuery and Ajax to delete a row on the page as well as a record in the database. The row on the page is successfully removed, but the PHP file isn't being called. I only have an echo statement in the PHP for error ch ...