cvanorman
cvanorman

Reputation: 148

Using close link in accordion content to change accordion icon

I'm not using jQuery UI for accordion. I wrote this quick script because jQuery UI is too bloated for what I need it for. I have setup a codepen with what I currently have, but I cannot get the close link within the content to change the src of the icon image in the header.

Here's what my markup looks like:

    <div class="accordion-item">
      <h3 class="accordion-label">test <img src="http://placehold.it/25x25"/></h3>
      <div class="accordion-content">
         Lorem Ipsum
         <span class="close">close</span>  
      </div>
    </div>

I'm trying to target the img tag in the h3 like this:

  $(this).parent('.accordion-content').prev('h3').children('img').attr('src','http://placehold.it/25x25');

The result I'm trying to get is that when I click the "close" link in the content of the expanded accordion-content, I want the accordion-content to collapse and then change the image src to the collapsed icon (using placeholders for sake of testing here).

I'm using jQuery 2.0.

CODEPEN: http://codepen.io/cvanorman/pen/YXpBRJ

UPDATED SOLUTION

   $(document).ready(function() {
       function profilesAccordion() {
       // Profiles Accordion
            $('.accordion-content').hide(); // Hide all Containers

            // Add 'active' class to first accordion item.
            $('.accordion-label').click(function() {
                $(this).siblings('.accordion-content').slideToggle();
                $(this).toggleClass('expanded');
            });

            $('.close').click(function() {
                $(this).parent('.accordion-content').slideToggle();
                $(this).closest('.accordion-item').find('.accordion-label').removeClass('expanded');
            });

        } profilesAccordion();
   });

Upvotes: 0

Views: 155

Answers (2)

Daemedeor
Daemedeor

Reputation: 1013

The best functionality to do in this case: use a data-attribute to let you know what state the dom is currently and trigger that everytime you close/open the accordion (or you can use a class and then use before/after on the css and image-background). Its because if you put "close" then you would also change when the item should toggle.

Upvotes: 1

Rudi
Rudi

Reputation: 2995

Try this:

 $(this).closest('.accordion-item').find('.accordion-label img').attr('src','http://placehold.it/25x25');

Upvotes: 1

Related Questions