Switch back to the original CSS when a different button is clicked by the user

I am facing an issue with my jQuery UI accordion where the arrow icons are not behaving as expected. Each header element has a right arrow that changes to a down arrow when clicked to display content, and reverts back to its original form when clicked again.

The problem arises when the user clicks on a new section header without closing the previous one. If I click on section 1, the arrow changes correctly. However, if I then click on section 2 without closing section 1, the arrow for section 1 remains in the downward position. I need it to revert back to a right-facing arrow whenever a different section header is clicked.

Below is the script I am using:

var toggleState = true;

$("#wholesale section").on("click", function () {
    if(toggleState) {
        $(this).find(".dropdown-arrow").html("▼");
        $(this).css("background", "#ececec");
    } else {
        $(this).find(".dropdown-arrow").html("►");
        $(this).css("background", "#f7f7f7");
    }
    toggleState = !toggleState;
});

Answer №1

You have the option to utilize the activate-event

$("#wholesale").on("accordionactivate", function (e, ui) {
    ui.oldHeader.find(".dropdown-arrow").html("▼");
    ui.oldHeader.css("background", "#ececec");
    ui.newHeader.find(".dropdown-arrow").html("►");
    ui.newHeader.css("background", "#f7f7f7");
});

Check out a demonstration: Fiddle


You may also want to consider implementing something similar to this:

var $sections = $("#wholesale section").on("click", function () {
    var $this = $(this).toggleClass('open');
    $sections.not(this).removeClass('open').css("background", "#f7f7f7").find(".dropdown-arrow").html("▼");

    if ($this.hasClass('open')) {
        $this.find(".dropdown-arrow").html("►");
        $this.css("background", "#f7f7f7");
    } else {
        $this.find(".dropdown-arrow").html("▼");
        $this.css("background", "#ececec");
    }
});

See it in action here: Fiddle

Answer №2

One approach is to assign a class to each button and then, upon clicking any button, reset all buttons to their default state before toggling the clicked button's arrow.

$("#wholesale section").on("click", function () {
    $(".buttons").each(function(){
        $(this).find(".dropdown-arrow").html("►");
        $(this).css("background", "#f7f7f7");
    })
    $(this).find(".dropdown-arrow").html("▼");
    $(this).css("background", "#ececec");
});

To simplify further, add a common 'button' class to all buttons. This eliminates the need for toggle functionality unless collapsibility is desired.

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

Some inquiries regarding the fundamentals of JavaScript - the significance of the dollar sign ($) and the error message "is not a function"

Teaching myself JavaScript without actually doing any explicit research on it (crazy, right?) has led to a few mysteries I can't quite crack. One of these mysteries involves the elusive dollar sign. From what I gather, it's supposed to be a con ...

Sometimes, in extremely rare instances, external stylesheets may fail to download or be properly applied

There have been very rare occurrences where major websites like Amazon and Facebook do not load a CSS file or apply the rules correctly, resulting in pages looking incomplete: I was recently asked to provide an internal explanation after receiving a compl ...

Is there a way to change the domain for all relative URLs on an HTML page to a different one that is not its current domain, including in HTML elements and JavaScript HTTP Requests?

I am dealing with a situation where my page contains "domain relative URLs" like ../file/foo or /file/foo within a href attributes, img src attributes, video, audio, web components, js ajax calls, etc. The issue arises when these URLs need to be relative ...

Two HTML elements positioned alongside each other with inline word wrapping

Apologies for the vague question title, which may not accurately reflect my requirements. This is one reason why I am struggling to find a solution through a simple Google search - I'm unsure of what terms to use. I am attempting to align some "label ...

Add up the entries of a JSONObject grouped by date pairs

My array is populated with JSON objects as shown below: [{ "date": "2015-10-02", "in": 79, "out": 78, "total": 157 }, { "date": "2015-10-05", "in": 80, "out": 55, "total": 135 }, { "date": "2015-10-02", "in": 70, ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

Implementing Google Calendar access token in JavaScript: A practical guide

I have a question about Google Calendar and I'm hoping you can assist me. I currently have an access_token from Google Calendar that has been stored in the localStorage. const googleAccessToken = e.vc.access_token; localStorage.s ...

Conflicting configurations in VS Code causing issues

Currently making adjustments to my JSON settings and everything is functioning correctly, however, I keep encountering this persistent error: "Expected comma jsonc(514)" Here's a snippet of my code that's causing the issue: "css.li ...

Unstyled Cards Failing to Receive Design

I am currently working on creating a prototype that utilizes two Bootstrap 4 cards to display information from a form and store related information from another form in the second card. The current layout of this setup can be observed below: https://i.sst ...

Authenticating and authorizing a client-side web application with a Remote NodeJS API integrating Passport.js

Displayed in the diagram below, there is an independent API Project operating on a server with a specific port, for example 3001, and a Web App running on a different server with another port, like 3002. https://i.sstatic.net/ovvAZ.png Running on port 30 ...

Using the EJS if-else statement to iterate through an array of items

I am working on rendering API data using Express (REST) and EJS (template engine) based on the value of the "status" field. If any item in the array has a status other than "CLOSED," it should be displayed, but if all items have the status set to "CLOSED," ...

Having trouble getting @vercel/ncc to work, keeps throwing a "Module not found" error

Recently, I have been attempting to follow a tutorial on creating custom GitHub actions using JavaScript from here. The tutorial suggests using the @vercel/ncc package to compile code into a single file if you prefer not to check in your node_modules folde ...

Tips for disabling automatic sliding in Bootstrap 5 carousel specifically on larger screens

I am working with a Bootstrap 5 carousel that I need to configure to stop autosliding on large screens, but maintain autoslide functionality on mobile devices. Is there a way to achieve this using only HTML and CSS/SCSS? I am aware of the data-bs-interval ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

403 Forbidden error occurs when making a post request in Django using AJAX

I'm having an issue with my register form and posting values to Django via Ajax. The POST request is returning a 403 forbidden error, while the GET request works fine. I've tried including {% csrf_form %} in the template, but it still shows 403 ...

Ways to eliminate extra spacing when search bar is expanded

My code is all contained within a header with the class 'example'. When the 'search' button is clicked, a div with the class 'search-bar' appears and its borders match those of the header. However, I want the search bar to ali ...

How to bind array elements in Vue.js

I am currently working with an array that contains various arrays and properties within it. My goal is to iterate through the array and generate new rows for each item in it. Here is a snippet of what I have been working on: var orderDetails = [ ...

Identify the name in the list by highlighting it when its content matches the text in a specific div id

I have an unordered list structured like this: <ul> <li id="projectrow_364"> <span>Forest</span> </li> <li id="projectrow_365"> <span>Life</span> ...

Collecting data from Jitsi

After setting up a Jitsi server using packages, I am now trying to log connection statistics to a database. Specifically, I want to store data about significant bitrate changes during video calls. Although I have some familiarity with JavaScript and WebRT ...

Only store arrays in Laravel that contain values by implementing a validation rule

How can I efficiently store arrays in Laravel? My database table only has columns for the first name, middle name, and last name. I have a form for entering information about different family members, but they all share the same column structure. I am cons ...