Issues with the functionality of the accordion feature when implemented with object-oriented JavaScript

https://i.sstatic.net/QABff.jpgI am currently working on implementing an accordion using object-oriented JavaScript. The issue I am encountering is that the toggle functionality does not work when I click. The desired output is to display content and change the icon to a plus sign when clicked, while closing other child elements. Initially, the first child should be set as active.

As I have just started learning object-oriented JavaScript, I would appreciate any feedback or suggestions for improvement in my code.

Accordion = {
accordionContent: '.accordion-s1 .accordion--content p',
accordionTitle: '.accordion--title',
init: function() {
   $(this.accordionTitle).click(this.toggleAccordion.bind(this));
},
toggleAccordion: function() {
    $(this.accordionContent).slideToggle();
    $(this.accordionTitle).removeClass("active");
    if($(this.accordionTitle).siblings().is(":visible")) {
        $(this.accordionTitle).siblings().slideDown();
                $(this).find('.fa.fa-times').toggleClass('plus');
        $(this.accordionTitle).addClass("active");
    }
}
}
$(document).ready(function(){
  Accordian.init();
});
.accordion-s1 .accordion--title {
  display: flex;
  flex-direction: row;
  padding: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  font-weight: 300;
  transition: all .25s ease;
  background-color: #2783e8;
  color: #ffffff;
}
.accordion-s1 .accordion--title h4 { flex:1;font-weight: 600;}
.accordion-s1 .aticon-times { padding: 5px;}
.plus {
  transform: rotate(45deg);
  transition: all .25s ease;
}
.accordion-s1 .accordion--content {
  padding: 10px 20px;
  background: whitesmoke;
}
<script src="https://use.fontawesome.com/a2e210f715.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="accordion-s1">
<div class="accordion--single">
<div class="accordion--title">
<h4>London Style</h4>
<span class="accordion--i">
<i class="fa fa-times aticon-times"></i>
</span>
</div>
<div class="accordion--content">
<p>Alienum phaedrum torquatos nec eu, vis detraxit periculis ex, nihil exp eten in mei. Mei an pericula euripidis, hinc partem ei est. Eos ei nisl graecis, vixet aperiri consequat an. Eius lorem tincidunt vix at, vel pertinax sensibus id. Pericula euripidis, hinc partem ei est.</p>
</div>
</div>
<div class="accordion--single">
<div class="accordion--title">
<h4>London Style</h4>
<span class="accordion--i">
<i class="fa fa-times aticon-times"></i>
</span>
</div>
<div class="accordion--content">
<p>Alienum phaedrum torquatos nec eu, vis detraxit periculis ex, nihil exp eten in mei. Mei an pericula euripidis, hinc partem ei est. Eos ei nisl graecis, vixet aperiri consequat an. Eius lorem tincidunt vix at, vel pertinax sensibus id. Pericula euripidis, hinc partem ei est.</p>
</div>
</div>
</div>

Answer №1

After reviewing your code, I noticed a couple of mistakes. The

$(this.accordionContent).slideToggle()
function is actually targeting all elements, as is the
$(this.accordionTitle).siblings()
.

Consider using the following revised code:

Accordion = {
accordionContent: '.accordion-s1 .accordion--content',
accordionTitle: '.accordion--title',
init: function() {
   $(this.accordionTitle).removeClass('active').eq(0).addClass("active");
   $(this.accordionContent).slideUp().eq(0).slideDown();
   $(this.accordionTitle).click(this.toggleAccordion.bind(this));
},
toggleAccordion: function(e) {

    if($(e.currentTarget).next($(this.accordionContent)).is(":visible")) {
        return
    }

    $(this.accordionTitle).siblings().slideUp();
    $(this.accordionTitle).removeClass('active');

    $(e.currentTarget).next($(this.accordionContent)).slideDown();
    $(e.currentTarget).addClass("active");
}
}
$(document).ready(function(){
  Accordion.init();
});

To add a plus sign, you will need to make adjustments in both the CSS and HTML title sections.

In the CSS:

.accordion--i .fa-times {
    display:inline-block;
}
.accordion--i .fa-plus {
    display:none;
}
.active .accordion--i .fa-times {
    display:none;
}
.active .accordion--i .fa-plus {
    display:inline-block;
}

In the HTML, you should include the following changes in every title within each block:

    <div class="accordion--title">
        <h4>London Style</h4>
        <span class="accordion--i">
            <i class="fa fa-times aticon-times"></i>
            <i class="fa fa-plus aticon-times"></i>
        </span>
    </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

Combine the link and action within mDataProp

Recently, I have transitioned to using Jquery Datatable for serverside pagination. One specific property I am dealing with is deviceMacAddress. In the past, when I was utilizing the display:table method, I had successfully created a hyperlink for the devic ...

Leverage the power of Three.js PositionalAudio to create an immersive cone of audio

Currently, I am in the process of creating an array of sounds utilizing PositionalAudio: var newSound = new THREE.PositionalAudio(listener); newSound.setBuffer(buffer); newSound.setRefDistance(20); newSound.autoplay = true; newSound.setLoop(true); s ...

Create an inline svg using only css, avoiding the need to define it within the html file

I have an HTML file that utilizes inline SVG. This allows me to assign classes to my SVG elements and style them using CSS. The code snippet below demonstrates how it is currently set up: <div> <svg class="icon" viewbox="0 0 512 512"> ...

How can I utilize the removeAttr('disabled') function in PHP by targeting a 'class' instead of an 'id'?

This PHP code creates a table with columns that have the same id and each row has a specific variable $i. while($row = mysqli_fetch_assoc($result)) { <tr> <td><input type='text' id='txt_id_".$i."' valu ...

What is the best way to incorporate new data into localstorage in a React application?

My attempt to implement and add data into local storage has not been successful as it keeps updating the old data instead of adding new ones. Can someone please explain how to store an array of objects entered by a user in local storage using React JS? ...

Is there a way to refresh an Angular component in Storybook using observables or subjects?

When I attempt to update my Angular component using a subject in Storybook by calling subject.next(false), I encounter an issue. The instance property of the component updates, but it does not reflect in the canvas panel. Here is my loading component: @Co ...

Conditionally display a button utilizing V-IF when a Firestore value evaluates to true

I am fetching data from my Firestore database and displaying them on cards. I want to add buttons to the card only if a specific value in the loaded object is true. { "Alarm": false, "Safety": true, "Battery": true }. For example, if the values are as ab ...

Utilizing jQuery's AJAX method for Access-Control-Allow-Origin

Here's the code snippet I'm working with: $.ajax({ url: url, headers: { 'Access-Control-Allow-Origin': '*' }, crossDomain: true, success: function () { alert('it works') }, erro ...

Quick access to HTML URLs without the need for page names

I'm having trouble finding the right search terms. Is there a way to simplify the URL links on my website? For instance: Current URL structure: websitename.com/about_us_what_we_do.php Desired URL structure: websitename.com/what-we-do Another e ...

I am having trouble getting my footer to align properly in a vertical position

My goal is to have my li elements remain on the same line, but unfortunately, they are not cooperating (they are aligning horizontally, but that's all). Here is the code snippet: <footer> <div class="container"> <div id="coi ...

Take out the "href" attribute from the parent element

I'm looking to disable the link for the "parent li" in a dropdown menu when viewed on mobile. Here's the HTML structure: <ul> <li class="parent"></li> <li class="parent"></li> <li class="parent"></li&g ...

Make sure to use the jQuery load function to specifically target and retrieve

Hello, I'm new to working with jQuery and I have a question about adding a vertical scrollbar to a jQuery modal window. Specifically, I want the scrollbar to appear when there is a large amount of text within the modal window. Can you guide me on wher ...

Serve an image in Node.js from a location outside of the public folder

Is there a way to display an image that is located outside of the public folder in my webroot? Here is my directory structure: Webroot --core ----views ----public <- Stylesheets and other images are stored here ------index.ejs <- I want to display f ...

What steps can I take to stop Highcharts from showing decimal intervals between x-axis ticks?

When the chart is displayed, I want to have tick marks only at integer points on the x-axis and not in between. However, no matter what settings I try, I can't seem to get rid of the in-between tick marks. Chart: new Highcharts.chart('<some i ...

Dynamic script appending encounters unforeseen challenges

After attempting to add a script either on click or after a time delay, I am encountering an issue where the script is not being appended. Strangely, if I remove the setTimeout function, the script gets added successfully. The same problem persists with ...

What is the most effective method for attempting an AJAX request again after it fails with the help of jQuery?

Here is a suggestion for handling ajax errors: $(document).ajaxError(function(e, xhr, options, error) { xhr.retry() }) An improvement could be incorporating exponential back-off strategies ...

Compose a tweet using programming language for Twitter

How can I send a message to a Twitter user from my .NET application? Are there any APIs or JavaScript code that can help with this task? Any assistance would be greatly appreciated. ...

Tell me the permissions that a user possesses in discord.js

I need help creating a command using Discord.js that can display a user's permissions. For instance, the command could be $permissions @user and it should output something like: "User permissions within this guild: " I'm unsure if ...

Updating a Mongoose document

I need help with a Node.js and mongoose Module project. I want to find a way to count the number of documents a user has and if they have more than 0 documents, I want to edit their existing document by adding the input text to it. Here is what I have so f ...

Mastering Ajax Technology with Five Dropdown Menus

I'm currently working on a form that includes 5 drop-down lists generated by PHP querying a MySql database. The lists are being populated correctly. My goal is to allow users to select an option from the list and have it automatically populate the fo ...