views:

150

answers:

2

Hi - I have a simple piece of jquery i am using to toggle the visibility of a div (below). What I'd like to add is some text and a little plus sign image that changes to different text and a minus sign image after the div is expanded. Here is my code:

jQuery

$(document).ready(function(){
  $(".toggle").click(function(){
  $(".hidden").slideToggle("slow");
  });
});

html

// this will be changed to  Hide Panel <img src="minusSign.gif"> 
// and doesn't have to live in a <p>
<p class="toggle">Show Panel <img src="plusSign.gif"></p>
<div class="hidden">
Blah Blah Blah
</div>

css

.hidden {display:none;}

Any advice on how to achieve what I'm looking for? Currently, the div toggles just fine, but the trigger text/image is static.

Thanks!

A: 

Use jQuerys .toggle() and .toggleClass()

$(document).ready(function(){
    $('.toggle').toggle(function(){
       $(this).slideToggle('slow').find('img').attr('src', 'minusSign.gif');
       $('div.hidden').hide();
    }, function(){
       $(this).slideToggle('slow').find('img').attr('src', 'plusSign.gif');
       $('div.hidden').show();
    });
});

If you want to change the text inside of .toggle aswell, you need to wrap that into a span for instance, and put it into the chain like

`.find('span').text('opened/closed');`
jAndy
I was wondering if who up-voted this... look at the effect, http://jsfiddle.net/7Lyrm/ ... where it should have been like this http://jsfiddle.net/RKsEm/
Reigel
Says the biggest js/jquery wannabe around at SO :P I didn't test that code, but, the main intension was the usage of .toggle(). The upvoter realized it I think, so you did not. Keep doing that.
jAndy
A: 

I can't help but noticed you need something like this...

$(".toggle").click(function(){
    $(".hidden").slideToggle("slow");
    $(this).html(function(i,html) {
        if (html.indexOf('Show') != -1 ){
           html = html.replace('Show','Hide');
        } else {
           html = html.replace('Hide','Show');
        }
        return html;
    }).find('img').attr('src',function(i,src){
        return (src.indexOf('plusSign.gif') != -1)? 'minusSign.gif' : 'plusSign.gif';
    });
});

and I baked you a demo

Reigel