0

I have a div ("panel" class) on my page that toggles open/closed on the click of a paragraph element ("flip" class), which has an image inside of it.

Here's the HTML:

<div class="panel">Contact info</div>
<p class="flip"><img src="images/contactExpand.png" />Expand</p>

And the jQuery:

$(".flip").click(function(){
    $(".panel").slideToggle("slow");
});

Everything works fine so far, but I want the image src to change to "contactCollapse.png" when the panel div is visible. This doesn't seem to do anything (image just stays the same):

if ($(".panel").is(":visible") == true) {
    $(".flip img").attr("src","../images/contactCollapse.png")
}
else {
    $(".flip img").attr("src","../images/contactExpand.png")
}

Am I missing something? Thanks for any help!

3 Answers 3

2

Make sure to check at the end of the animation, as it'll be visible at the start no matter which direction you're animating, like this:

$(".flip").click(function(){
  $(".panel").slideToggle("slow", function() {
    $(".flip img").attr("src", $(this).is(":visible")
        ? "../images/contactCollapse.png"
        : "../images/contactExpand.png");
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

just to add to this answer, this is the concept of a callback function, executing after the original function completes. Very useful to chain actions together in jQuery.
0

Are you sure the URL is correct? You have images/contactExpand.png in the original code and ../images/contactExpand.png in your javascript.

Also - are your sure this code works correctly? $(".panel").is(":visible") == true. Maybe if you change it to $(".panel:visible").length == 1.

1 Comment

For the URL, my javascript is inside a folder so I needed to navigate back up a directory. However, I tried changing the URL and it still didn't change anything, so I don't think the jQuery code is even working at all. I tried changing the code to what you suggested and it still wasn't changing anything.
0

That's because the status isn't change until after the slide is performed. Try placing your code in the callback of the slideToggle:

$(".flip").click(function(){
    $(".panel").slideToggle("slow",function(){
        if ($(".panel").is(":visible")) {
            $(".flip img").attr("src","../images/contactCollapse.png")
        }
        else {
            $(".flip img").attr("src","../images/contactExpand.png")
        }
    });
});

2 Comments

@NIckCraver hit it before I did, didn't get the "There is an answer already posted" message while I was composing. ;p
Yes that solution (as well as your version) worked. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.