Search code examples
jquerytoggleexpressionengineeach

Proper set up for using slideToggle


Guys i'm trying to get a list of posts and it's content not to display on page load but within each div there is a expand button that would expand just that particular post. Here is the code that I have so far:

<div class="postEntry">

    <div class="collapsibleContent">
         <div class="postContent"></div>
    </div>

    <div class="actionDiv">
        <span id="actionWording">Read More</span>
        <a href="#" id="actionLink" class="open"></a>
    </div>

</div>

<div class="postEntry">

    <div class="collapsibleContent">
         <div class="postContent"></div>
    </div>

    <div class="actionDiv">
        <span id="actionWording">Read More</span>
        <a href="#" id="actionLink" class="open"></a>
    </div>

</div>

I would like to make actionDiv clickable so that the content will display but ALSO have the wording within actionWording change to COLLAPSE if content is expanded. actionLink is an anchor tag that has a background image set by css and the class open close.

This is what I have for JS:

jQuery(function()
{

  $('.collapsibleContent').each(function() {
    $(this).css('display', 'none');
  });

  $('.actionButton').click(function() {
    $(this).next('.collapsibleContent').slideToggle('fast')
    return false;
  });

});

Solution

  • jsBin demo

    look for .prev() and use .hide() method, and you don't need return false unless you use anchors, but in that case I'd suggest to use event.preventDefault()

    $(function(){
    
      $('.collapsibleContent').hide();
      
      $('.actionButton').click(function( ev ) {
          ev.preventDefault();
    
          var visible = $(this).prev('.collapsibleContent').is(':visible'),
             slideTog = visible?'slideUp':'slideDown',
                  txt = visible?'EXPAND':'COLLAPSE';
           
          $('.collapsibleContent').slideUp().next('.actionButton').text('EXPAND');
          
          $(this).text( txt ).prev('.collapsibleContent')[slideTog]();
    
      });
       
    });