Tips for effectively closing div elements

How can I modify this accordion to close when a user clicks on another link, and also change the image of the open "p" tag? Currently, clicking on a link toggles the content and changes the image. However, what I am struggling with is closing the previously opened "p" tag. It currently functions like an onclick toggle for the content.

I attempted to add code that closes all the "p" tags but doesn't revert the image back to the default one with the plus icon.

$('p').hide();

$(this).bind('keypress click', function(e) {
  e.preventDefault();
  $('p').hide();
  var $icon = $(this).find('.icon'); 
  if($icon.hasClass('first-image'))
  {
    $icon.removeClass('first-image').addClass('second-image');
  }
  else
  {
    $icon.removeClass('second-image').addClass('first-image');
  }
  $(this).next('p').slideToggle();
});
<ul class="accor">
  <li><a href="#"><span class="icon second-image"></span> Item 1</a> 
    <p style="display:block"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li> 
  <li><a href="#"><span class="icon first-image"></span> Item 2 </a>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li> 
</ul>

The problem I'm facing is with Item 1 - it closes but the image remains as (--), instead of changing back to (+).

https://i.sstatic.net/1DAB7.jpg

Answer №1

It seems that in order for the code snippet to work correctly, you should consider specifying a as a selector instead of using this.

Here is an example:

$('a').bind('keypress click', function(e) {
  e.preventDefault();
  $('p').hide();
  $('.icon').removeClass('second-image').addClass('first-image');
  var $icon = $(this).find('.icon'); 
  var $p = $(this).next('p').slideToggle();
  if($p.is(':visible'))
  {
    $icon.removeClass('first-image').addClass('second-image');
  }
  else
  {
    $icon.removeClass('second-image').addClass('first-image');
  }
});
li {
  list-style:none;  
}

p {
  display:none;  
}

.icon:before {
  display: inline-block;
  font: normal normal normal 14px/1 FontAwesome;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  content: "\f067"
}

.icon.second-image:before {
  content:"\f068";  
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="accor">
  <li><a href="#"><span class="icon second-image"></span> Item 1</a> 
    <p style="display:block"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li> 
  <li><a href="#"><span class="icon first-image"></span> Item 2 </a>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li> 
</ul>

The code snippet may not be functional here, so I have created a bin for reference:

Answer №2

$(document).ready(function() {
//ACTION WHEN ACCORDION BUTTON IS CLICKED
    $('.accordionButton').click(function() {

        //REMOVE 'on' CLASS FROM ALL BUTTONS
        $('.accordionButton').removeClass('on');

        //CLOSE ALL OPEN SLIDES
        $('.accordionContent').slideUp('normal', function(){
            $(this).prev().find('.img1').removeClass('img2');
        });

        //IF THE CONTENT IS HIDDEN, SHOW IT
        if($(this).next().is(':hidden') == true) {

            //ADD 'on' CLASS TO CLICKED BUTTON
            $(this).addClass('on');

            //OPEN THE SLIDE
            $(this).next().slideDown('normal', function(){
                $(this).prev().find('.img1').addClass('img2');
            });
        }
    });

    //HIDE ALL SLIDES ON PAGE LOAD
    $('.accordionContent').hide();
});

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

The session becomes obsolete when redirecting back to the previous page

When attempting to redirect using the http referrer after storing a value in Session in php, I noticed that the Session becomes null. Is there a method to maintain the session even when utilizing the http referrer? ...

CSS animations are only functional when the Developer Tools are activated

I recently implemented a transition to uppercase in CSS, but it seems to only work when I open dev tools in Mozilla and not at all in Chrome. This is my first attempt at using animations in CSS, so any feedback on my code is appreciated. I'm curious ...

CSS Grid ensures uniformity in the spacing between columns

Is there a way to ensure the spacing between items is consistent? I attempted to use grid-column-gap, but the gap varies because the number of items on each row differs. The first and third rows have a larger gap compared to the second row, which has the ...

Is there a way to access and parse a CSV file from a URL within a Next.js project?

Currently working on a Next.js application available here. The task at hand requires reading a CSV file from a specific URL within the same repository in multiple instances. Unfortunately, I am encountering difficulties retrieving this data. You can locate ...

update the dropdown values in the database by submitting the form

Members sign up for the website. The administrator will log in and access a list of users. I am attempting to provide an option for the admin to select a checkbox and update the user's status through a dropdown menu submission. When I tested the code ...

The function `map` cannot be applied to `this.state.[object]`

It seems like I might be overlooking a simple mistake, but I keep encountering this.state.iata.map is not a function , even though I have bound the context to all functions where I need to access that state. Additionally, the iata state is an array, s ...

Customized slider in jQuery UI allowing users to select height using a scaled ruler

Currently, I am tackling a challenging math problem related to adjusting the height selector input. Essentially, I have implemented a jQuery UI slider for choosing a height. It operates in inches and ranges from 0 to 120 (equivalent to 10 feet in height). ...

Incorporate vanilla JavaScript and HTML into a Next.js application

I am facing an issue where I have a file that contains JavaScript and HTML code, which needs to be rendered within a Next.js application. The challenge is that the code in the file cannot be converted to JSX, and React Helmet does not seem to render anythi ...

The Bootstrap accordion-toggle incorrectly displays the content symbol (+/-) upon initial page load

Hey there, I've implemented the accordion-toggle code below on my visualforce page. Everything is working smoothly with the collapsible toggle, except for one issue. When loading or refreshing the page for the first time, the collapsed panel shows the ...

Dynamic React animation with sliding elements

When jumping between the second and third "page" of content, I am unable to determine the reason why it is happening. The content is displayed as an absolute position. Check out the sandbox here: https://codesandbox.io/s/nostalgic-bhabha-d1dloy?file=/src ...

Retrieve() displays solely the initial array within an object

I am facing an issue with my Redux/React project where I am calling an API to search for a specific ID based on the useParams value. I suspect the problem lies in my return statement return data.hero.find(hero => <Hero key={hero.id} hero={hero} /> ...

Style the "focus" pseudo-class of an input element using Vue programmatically

Currently, I have been utilizing event listeners to manipulate the :focus pseudo-class of an input element: const element = document.getElementById("myElementID"); element.addEventListener("focus", (e) => { e.target.style.borderCo ...

What is the correct way to load a column of images without affecting the readability of the text alongside them? (see image below)

https://i.stack.imgur.com/rBL50.png Whenever my page loads, there is a card with a vertical list of images. Due to the loading time of the images, the text appears first and gets squished as shown in the provided screenshot. Is there a way for the text to ...

When I expand one panel, I want to automatically close any other opened panel to ensure only one section is expanded at a

I'm experiencing an issue with the Bootstrap 4 accordion. Currently, when I open a collapsed section in the accordion, it remains open even when I click on another collapsed section. What I actually want is for the previously opened section to close ...

What is the best way to combine height and min-height in order to ensure that a div always extends to the bottom and keeps

I've tried multiple suggestions without success so far. In my website, I have a main section with white background centered on the page. It stretches nicely to the bottom using flex. See image: https://i.sstatic.net/RmJ2o.png However, there's a ...

What is the most effective method for storing an object in React?

I am facing an issue with storing my Object of my Checkout-Cart in a React Variable. I attempted to use the useState Component, but unfortunately, it did not work. Here is the object that I receive from my NodeJs Backend : [ { product_uuid: '3b ...

Is it possible to merge upload file and text input code using AJAX?

For my form submissions using jQuery and Ajax, I'm trying to figure out how to send both data and files together. Currently, I have the following code: $("#save-sm").bind("click", function(event) { var url = "sm.input.php"; var v_name_sm = $(&ap ...

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 ...

What could be causing the problem with my CSS background-image being referenced correctly?

Everything seems to be in order: background-image: url(./dir/img.jpg); However, I encounter a 404 error when attempting to reference an image using this approach: index.html <div style="--url: url(./dir/img.jpg);"></div> css backg ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...