0

Trying to toggle between two images when clicking on a heading. For starters, I haven't even been able to get them to show. Any ideas?

<h2 class="expand" id="content-1" style="cursor:pointer;" value="One">Click to expand One</h2>
<h2 class="expand" id="content-2" style="cursor:pointer;" value="Two">Click to expand Two</h2>

Tried below but nothing so far.

 $('.expand').on('click', function() {
              if($(this).text().indexOf('expand') >0 )
              $(this).text('Click to collapse ' + $(this).attr("value"));
                $('.expand').css('background-image', 'url(' + img/arrow-up.gif + ')');
               else
                   $(this).text('Click to expand ' + $(this).attr("value"));
                 $('.expand').css('background-image', 'url(' + img/down-up.gif + ')');  
            });

and

$(this).text('Click to collapse ' + $(this).attr("value") + $(this).css...);
3
  • your image css is commented out. FYI, you'd typically handle this via an image sprite, then instead of swapping the CSS directly, just swap the class name that repositions the sprite. Commented Feb 14, 2014 at 21:54
  • Now it's uncommented but you're trying to append a variable with the name of "img/arrow-up.gif". That won't work. It should all be just one string. Commented Feb 14, 2014 at 21:56
  • @Diodeus syntax can still be the probelm. (' + img/arrow-up.gif + ') is correct? @DA fixed Commented Feb 14, 2014 at 21:56

2 Answers 2

1

Your easiest option is to switch class names and define the images in CSS.

$('.expand').toggleClass('someClass')


.someClass {
     background-image:url(...);
}
Sign up to request clarification or add additional context in comments.

Comments

0

This:

 $('.expand').css('background-image', 'url(' + img/arrow-up.gif + ')');

Likely should be this:

 $('.expand').css('background-image', 'url("img/arrow-up.gif")');

But I'd second Diaodeus and that this should be spec'd in the CSS and your jQuery simply swapping class names. I'd also turn your images into a sprite so it's just one image.

Comments

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.