Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Toggle Show/Hide w/Multiple DIV ID's

CODE:

$(document).ready(function() {

    $('.toggle').hide();

    $('.show').click(function(){

        $('.toggle').toggle('slow'); 

        $(this).attr('src','images/checkmark2.jpg');

    },function(){

        $('.toggle').toggle('slow'); 

        $(this).attr('src', 'images/checkmark1.jpg');

        return false;
    });
});

HTML:

<img class="show" src="images/checkmark1.jpg"/>Header Text

Hidden Text is in a div class "toggle" to be seen when you click on the checkmark1.jpg image. With multiple "toggle" div classes, they all expand at once.

When "toggle" is set to ID # in the Script and HTML, they expand independently (as how I would like), but you cannot use the same DIV ID # Name throughout. So how would i change the code to use multiple toggle DIV IDs; or use "toggle" classes that don't expand every one at once ???

HERE is a direct link to my code. http://www.flipflopmedia.com/test/ToggleTEST_html.txt When I try to insert it, it's being rendered and not displaying so that you can actually see it. Yes, I'm using the code button 'enter code here' to apply it, not working!

like image 331
flipflopmedia Avatar asked Dec 05 '25 10:12

flipflopmedia


2 Answers

Since you didn't provide any HTML to work from, I put some together with script that works

HTML

 <img class="show" src="images/checkmark1.jpg" /><span>Header Text 1</span>
 <div class="toggle">This is some hidden text #1</div>

 <img class="show" src="images/checkmark1.jpg" /><span>Header Text 2</span>
 <div class="toggle">This is some hidden text #2</div>

Script (updated to work with your HTML)

$(document).ready(function(){
 $('.toggle').hide();
 $('.show').click(function(){
  var t = $(this);
  // toggle hidden div
  t.next().next().toggle('slow', function(){
   // determine which image to use if hidden div is hidden after the toggling is done
   var imgsrc = ($(this).is(':hidden')) ? 'images/checkmark1.jpg' : 'images/checkmark2.jpg';
   // update image src
   t.attr('src', imgsrc );
  });
 })
})
like image 173
Mottie Avatar answered Dec 07 '25 12:12

Mottie


The "click" function only allows you to add one function (the one that's fired when you click the selected element(s)). But you're passing it two. You probably want to use the "toggle" function instead. See this question for more info:

jQuery Toggle State

like image 42
Ian Varley Avatar answered Dec 07 '25 10:12

Ian Varley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!