1

I have this simple toggle function to open/close information. I want to add a image next to it so that it shows expanded or closed. I tried this method but nothing is happening. What am I missing?

$('#slick-software').click(function() {
   $('#slickbox-software').toggle(400);
   $('#slick-img').attr('src') == "/images/up.png" ? "/images/down.png" : "/images/up.png";
   return false;
});

...
...

<a href="#" id="slick-software">
    <img id="slick-img" src="/images/up.png" border="0" align="absmiddle" />&nbsp;&nbsp;
        <b>Software</b><br>
    </a>
<div id="slickbox-software">
    text here
</div>

Thanks for your help.

user1457393
  • 31
  • 1
  • 3

4 Answers4

2

A nicer solution would be to use CSS for your up/down image, you could include it as a background image on the #slick-software element (with some left padding applied to it). You could then toggle a class in your click handler to either change the background image, or preferably change the background position of a CSS sprite. I also prefer to call preventDefault than returning false to override the default click behaviour as returning false stops event bubbling.

$('#slick-software').click(function(e) {
   $('#slickbox-software').toggle(400);
   $(this).toggleClass("expanded");
   e.preventDefault();
});

Then in your css, something like:

#slick-software{
  display: inline-block;
  padding: 0 0 0 20px;
  background: url(img/toggle.png) no-repeat 0 0;
}

#slick-software.expanded{
  background-position: 0 -50px;
}
Community
  • 1
  • 1
thebiffboff
  • 948
  • 5
  • 8
1

The bug is here, I think:

$('#slick-img').attr('src') == "/images/up.png" ? "/images/down.png" : "/images/up.png";

You just check 'src' attribute here, but don't actually change it.

Use the following instead:

var newSrc = $('#slick-img').attr('src') === "/images/up.png" ? "/images/down.png" : "/images/up.png";
$('#slick-img').attr('src', newSrc);
raina77ow
  • 103,633
  • 15
  • 192
  • 229
0

try:

var src_img = ($('#slick-img').attr('src')=="/images/up.png") ? "/images/down.png" : "/images/up.png";
$('#slick-img').attr('src', src_img)
mgraph
  • 15,238
  • 4
  • 41
  • 75
0

You want to force the image to refresh once you have changed the src. There's a question here which is very similar with a few decent answers:

How to refresh the src of <img /> with jQuery?

Community
  • 1
  • 1
peacemaker
  • 2,541
  • 3
  • 27
  • 48