web design
  • August 06, 2009 by David

    JQuery Accordion Style Toggle

    Goal: Build an accordion style toggle for a page with multiple info boxes.

    Example: http://www.xillent.com/pipeline/sales_info.asp?cid=29

    First Attempt: Use jquery script:

    <script type="text/javascript">
    $(document).ready(function() {
    $("#ContentWrapper div.AccordionHeader").click(function() {
    $(this).next("div.ContentBody").slideToggle(300).siblings("div.ContentBody").slideUp("slow");
    });
    });
    </script>
    

    Problem with First Attempt: We want the image inside the header to show “minus” when we click on it. However, the image inside the header does not change and always shows “plus.”

    We tried countless solutions for over 5 hours, including “$(this).siblings, $(this).next, $(this).parents, and other combinations. Finally, we figured out the solution:

    Final Solution: $(this).find(“.InputHeaderIcon”).attr(“src”,”assets/icons/min.gif”);

    The “find” returned the first matched element within a dom, and now we can toggle the images correctly.

    <script type="text/javascript">
    $(document).ready(function() {
    $("#ContentWrapper div.AccordionHeader").click(function() {
    $(this).next("div.ContentBody").slideToggle(300).siblings("div.ContentBody").slideUp("slow");
    $(".InputHeaderIcon").attr("src","assets/icons/max.gif");
    $(this).find(".InputHeaderIcon").attr("src","assets/icons/min.gif");
    });
    });
    </script>
    
     

    Leave a Comment

    • required  
    • required  
    •