jQuery Toggle switch images

Posted by Sixfoot Studio on Stack Overflow See other posts from Stack Overflow or by Sixfoot Studio
Published on 2010-06-07T12:48:06Z Indexed on 2010/06/07 12:52 UTC
Read the original article Hit count: 161

Filed under:
|
|

Hi Guys,

I have a situation where I am not understanding jQuery's Toggle.

I have two buttons, both of them open the same content and when you click on either button the content should open or close and the attribute changes the button from open to closed. (So both buttons do the same function).

Only thing is, when I click on the top button and it opens my content and then click on the lower button to close it, the image attributes are switched incorrectly.

Here's a very stripped down version of what my code looks like and I would appreciate some help.

<script language="javascript" type="text/javascript">
    $(function () {

        var open = false;

        $("#button1, #button2").toggle(
            function () {
                open = true;
                $("#button1").attr("src", "images/btn-open.gif");
                $("#button2").attr("src", "images/btn-open.gif");
            },
            function () {
                if (open) {
                    $("#button1").attr("src", "images/btn-closed.gif");
                    $("#button2").attr("src", "images/btn-closed.gif");

                } else {
                    $("#button1").attr("src", "images/btn-open.gif");
                    $("#button2").attr("src", "images/btn-open.gif");

                }
                open = false;

            }
        );


    });
</script>

<img id="button1" src="images/btn-open.gif"></img>
<br />
<br />
<br />
<br />
<img id="button2" src="images/btn-open.gif"></img>

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about image