Updating Icons on a Jquery Accordion

I need help modifying an icon to change when clicking on a specific section. Currently, I have the functionality set up to change all accordion icons when opening or closing. However, I am struggling to make it so that only the icon of the selected section changes without affecting the others.

Here is the code snippet:

https://jsfiddle.net/t2beth2L/2/

Answer №1

The contentAreas variable in your Fiddle represents a collection of all content areas. By binding events like this:

contentAreas.on({
    hide: ...,
    show: ...
});

You are essentially setting up the functionality where the hide/show actions will be triggered for each content area when the Show/Hide All button is clicked.

Once you determine whether an area is being hidden or shown (based on the event), simply assign the correct icon (- or +) to that particular section.

It makes no difference whether the user triggers this action via the global Show/Hide All button or by individually clicking on a header.

var headers = $('#accordion .accordion-header');
var contentAreas = $('#accordion .ui-accordion-content ').hide();
var expandLink = $('.accordion-expand-all');

headers.click(function() {
  var panel = $(this).next();
  var isOpen = panel.is(':visible');

  panel[isOpen ? 'slideUp' : 'slideDown']()
    .trigger(isOpen ? 'hide' : 'show');

  return false;
});

expandLink.click(function() {
  var isAllOpen = $(this).data('isAllOpen');

  contentAreas[isAllOpen ? 'hide' : 'show']()
    .trigger(isAllOpen ? 'hide' : 'show');
});

contentAreas.on({
  show: function($event) {
    var isAllOpen = !contentAreas.is(':hidden');
    if (isAllOpen) {
      expandLink.text('Close All')
        .data('isAllOpen', true);
    }

    // display the 'hide' icon for the current content area
    setIcon($event.currentTarget, '-');
  },

  hide: function($event) {
    var isAllOpen = !contentAreas.is(':hidden');
    if (!isAllOpen) {
      expandLink.text('Open All')
        .data('isAllOpen', false);
    }

    // display the 'show' icon for the current content area
    setIcon($event.currentTarget, '+');
  }
});

function setIcon(sectionEl, sectionIcon) {
  var currentSection = $(sectionEl);
  var currentSectionHeader = currentSection.prev();
  currentSectionHeader.find('.plusminus').text(sectionIcon);
}
body {
    font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
    font-size: 62.5%;
}

.accordion-expand-holder {
    text-align: center;
    padding: 10px;
}

.container-accordion{
    padding-top: 8em;
    width: 60%;
    margin: auto;
}

.ui-accordion-content > p {
    margin-top:0px;
    margin-bottom:0px;
    padding-top:5px;
    padding-bottom:5px;
}

#accordion > h2 {
    cursor:pointer;
}

.plusminus {
    float:right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container-accordion">
  <p class="accordion-expand-holder">
    <a class="accordion-expand-all" href="#">Open All</a>
  </p>
  <div id="accordion">

    <h2 class="accordion-header ui-accordion-header">Title 1 <span class="plusminus">+</span></h2>
    <div class="ui-accordion-content">
      <p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integerut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sitamet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo utodio. Curabitur malesuada. Vestibulum
        a velit eu ante scelerisque vulputate.
      </p>
      <p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integerut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sitamet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo utodio. Curabitur malesuada. Vestibulum
        a velit eu ante scelerisque vulputate.
      </p>
    </div>
    <h2 class="accordion-header ui-accordion-header">Title 2 <span class="plusminus">+</span></h2>
    <div class="ui-accordion-content">
      <p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integerut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sitamet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo utodio. Curabitur malesuada. Vestibulum
        a velit eu ante scelerisque vulputate.
      </p>
      <p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integerut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sitamet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo utodio. Curabitur malesuada. Vestibulum
        a velit eu ante scelerisque vulputate.
      </p>
      <p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integerut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sitamet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo utodio. Curabitur malesuada. Vestibulum
        a velit eu ante scelerisque vulputate.
      </p>
    </div>
    <h2 class="accordion-header ui-accordion-header">Title 3 <span class="plusminus">+</span></h2>
    <div class="ui-accordion-content">
      <p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integerut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sitamet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo utodio. Curabitur malesuada. Vestibulum
        a velit eu ante scelerisque vulputate.
      </p>
    </div>
  </div>;

</div>

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

Concealing the Footer on Mobile Websites in Muse UI When the Keyboard Appears

In this project, I am using vue.js along with muse.ui and only incorporating JavaScript and CSS without the jQuery library. Currently, the footer position always ends up on top of the keyboard whenever an input field is focused. Is there a way to ensure th ...

When the input field is cleared, JavaScript will not be able to recognize its contents

Having an issue with my function that fetches results, <script language="javascript"> function fetchResult(value){ url="ajax_fetch.php?st=usr&q="+value; ajax(url); } fetchResult(" "); </script&g ...

Is there a way to reduce the spacing between these child containers when they wrap?

I'm looking to reduce the space between my child divs when they wrap It seems like the issue lies within the media query * { margin: 0; padding: 0; box-sizing: border-box; } html { font-size: 10px; width: 100%; } html, bo ...

Is the presence of a potential leak suggested by this arrangement in the heap snapshot retainer hierarchy

While analyzing a Heap snapshot, I came across a retainer hierarchy that looks like this: https://i.sstatic.net/Zg3bJ.png Is it possible that the MuiThemeProviderOld element (highlighted in yellow and from the @material-ui/core library) is causing a memo ...

Bootstrap 4 Alpha Grid does not support aligning two tables side by side

When working with Bootstrap 4, I am aware that the .col-xs classes have been removed. Instead of using .col, I have tested it on Bootstrap 3.5 which is currently being utilized. <div class="col-xs-4"> Table content for left ...

What is the best way to retrieve classes from arrays and apply styling to them using javascript?

Imagine having 3 unique classes: alpha, beta, and gamma. Each class contains 3 individual div elements like so: <div class="alpha"></div> <div class="alpha"></div> <div class="alpha"></div> <div class="beta">< ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

Waiting for an Element to Become Visible in Selenium-Webdriver Using Javascript

When using selenium-webdriver (api docs here), how can you ensure that an element is visible before proceeding? Within a set of custom testing helpers, there are two functions provided. The first function successfully waits for an element to exist, howeve ...

In React Router, redirect when location.state is not defined

import React, { useState } from "react"; import { Redirect } from "react-router-dom"; function Update(data) { if(!data.location.state) return <Redirect to="/"/> const [name, setName] = useState(dat ...

Is your Javascript failing to update window.location.search?

Looking to update the URL search parameters when a user enters them in the search panel on a page. Currently attempting: $( document ).ready(function() { if ($('.o_website_license_search_panel').length) { $('.o_website_license_s ...

Displaying numerous Google maps on a single webpage featuring distinct collections of location markers

Currently, I am utilizing the Google Maps API to showcase two distinct Google maps on a single page. Each map comes with its own set of unique markers that are dynamically generated via Wordpress from various custom post types. While one map is successful ...

Leveraging Axios for form data submission

Is it possible to serialize data from an HTML form element and then post the data using a Post request with Axios? Below is the event code triggered when a button click occurs to submit the post: function form_submission(e) { var data = document.getEleme ...

Utilizing Vuetify color variables in combination with ternary operators: A guide

I'm experimenting with conditional logic to dynamically change the background color of a button. I've seen examples using the ternary operator to do so, but haven't come across any that utilize color variables defined in the theme options. I ...

Encountering a bug: "Undefined property" issue when working with Web Sockets in React Native

I'm a beginner in React Native and Java Script development, and I'm facing an issue while trying to retrieve a JSON object and display it on the client side. I keep getting a "cannot read property of undefined" error when using websockets instead ...

Eliminating an unwelcome gap between two div elements

I couldn't find anything on Google, so I searched this site and came across a similar topic Unwanted space between divs. I tried applying margin:0px; in several places, but there is still space between the two divs. Here's my HTML: <!DOC ...

Issue with CORS on Next.js static files leading to broken links on version 10.1.4

Currently, my Nextjs application is fetching its static files from Cloudfront. During deployment, I upload the /static folder to S3. After updating to version 9, I encountered a strange problem where some of my CSS files are triggering a CORS error: Acces ...

Issue with PHP page not properly connecting to the recently updated CSS file

Yesterday, I successfully linked my CSS in the head tag right below the title tag using this code: <link href="css/main.css" rel="stylesheet"> Yesterday, everything was working fine with the styles. However, today when I try to add new styles, the ...

What are some ways to prevent a submit event from occurring?

When my form is submitting, I am executing a function. $('#form-target').submit(function(){ makechange(); return false; }); However, there are situations where I need to prevent this event from happening. ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

Mapping the changes in the checkbox of a material tree node

Check out this demo on StackBlitz: Tree View I'm having issues with the tree not displaying as desired. I would like it to look like this: Manager Sublist Manager 1 Manager 2 Manager 3 Could you please review and provide some advic ...