Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hide and show toggle div with plus and minus icon

I have the code working for the show and hide the div. How would I add two different icons as a sprite image for when the show and hide are active?

For example: + icon for show me, then a - icon for hide me.

Here is the code, I have: http://jsfiddle.net/BLkpG/

$(document).ready(function(){
   $(".slidingDiv").hide();
   $(".show_hide").show();

    $('.show_hide').click(function(){
    $(".slidingDiv").slideToggle();
  });
});

Need to change image to the above when toggled to a + or -.

Thanks

like image 668
pab Avatar asked Jan 06 '13 20:01

pab


People also ask

How do I toggle a div using jQuery?

To toggle a div visibility in jQuery, use the toggle() method. It checks the div element for visibility i.e. the show() method if div is hidden. And hide() id the div element is visible. This eventually creates a toggle effect.

How do I toggle between hide and show in jQuery?

jQuery toggle() MethodThe toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

How do I toggle icons in jQuery?

click(function(){ $('#display_advance'). toggle('1000'); $(this).

What is jQuery code $( P Hide () do?

The jQuery hide() method is used to hide the selected elements. Syntax: $(selector). hide();


2 Answers

Try something like this

jQuery

$('#toggle_icon').toggle(function() {

    $('#toggle_icon').text('-');
    $('#toggle_text').slideToggle();

}, function() {

    $('#toggle_icon').text('+');
    $('#toggle_text').slideToggle();

});

HTML

<a href="#" id="toggle_icon">+</a>

<div id="toggle_text" style="display: none">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>

DEMO

like image 126
Enve Avatar answered Oct 04 '22 13:10

Enve


I would say the most elegant way is this:

<div class="toggle"></div>
<div class="content">...</div>

then css:

.toggle{
 display:inline-block;
height:48px;
width:48px;  background:url("http://icons.iconarchive.com/icons/pixelmixer/basic/48/plus-icon.png");
}
.toggle.expanded{
  background:url("http://cdn2.iconfinder.com/data/icons/onebit/PNG/onebit_32.png");
}

and js:

$(document).ready(function(){
  var $content = $(".content").hide();
  $(".toggle").on("click", function(e){
    $(this).toggleClass("expanded");
    $content.slideToggle();
  });
});

FIDDLE

like image 26
Vytautas Butkus Avatar answered Oct 04 '22 14:10

Vytautas Butkus