Search code examples
htmljquerytoggle

Expanding div with jquery, toggle with buttons


I have a nice working script where you can expand and collapse a div with two "text"-buttons. I want to replace those with an image for expand (expand.png) and another for collapse (collapse.png).

<script type="text/javascript">
$(document).ready(function(){
    $("#expanderHead").click(function(){
        $("#expanderContent").slideToggle();
        if ($("#expanderSign").text() == "+"){
            $("#expanderSign").html("−")
         }
        else {
            $("#expanderSign").text("+")
        }
    });
});

Can't seem to figure out how to implement the img in the code... If anyonde can help, that would be awesome!


Solution

  • Let's suppose your #expanderHead is an <img>, then you can change the source like below:

    $(document).ready(function(){
        $("#expanderHead").click(function(){
            $("#expanderContent").slideToggle();
            if ($("#expanderSign").attr("src") == "expand.png"){
                $("#expanderSign").attr("src","collapse.png");
            }
            else {
               $("#expanderSign").attr("src","expand.png");
            }
        });
    });