Kratos
Kratos

Reputation: 55

jQuery Toggle hide when clicked again

Edit: I do want the other sigs to hide if another one is opened.

I'm setting up a toggle for my Forum's signatures, I got what I wanted with the toggle but I can't figure out how to make it hide when you click toggle again.

function toggleSig(divId) {
   $('.forum_signature').each(function(index) {
      if ($(this).attr("id") == divId) {
          $(this).show(200);
      }
      else {
          $(this).hide(600);
      }
   });
}

https://jsfiddle.net/4yg83kru/1/

Any ideas on how I can make the toggle hide when clicked again? (I'm new at the JS/jQuery stuff)

Upvotes: 2

Views: 128

Answers (3)

Franco
Franco

Reputation: 2329

You could use the toggle event :

function toggleSig(divId) {
    $('.forum_signature').each(function(index) {
        if ($(this).attr("id") == divId) {
            $(this).toggle(200);
        }

    });
}

NOTE: this is not the only way to do that, but it seems to me the easy way for you.

This one only opens the clicked one:

function toggleSig(divId) {
   $('.forum_signature').hide()
    $('.forum_signature').each(function(index) {
        if ($(this).attr("id") == divId) {
            $(this).show(200);
        }

    });
}

You can check it here:

https://jsfiddle.net/5xkvew4k/

Upvotes: 0

Shyju
Shyju

Reputation: 218732

Passing in the id of the item and looping through all the items and doing something looks a little dirty. You can make your code a little more generic. Give a css class to your anchor tag.

<a class="myA">Toggle Signature</a>
<div id="1" class="forum_signature" style="display:none;">
    Signature
</div>
<a class="myA">Toggle Signature</a>
<div id="2" class="forum_signature" style="display:none;">
    Signature 2
</div>

Now the javascript to handle the hide and show

$(function(){

  $(".myA").click(function(e){
     e.preventDefault();

     var c= $(".forum_signature:visible"); //Get currently visible one       
     $(this).next().toggle(); //Show the current one
     c.hide(); // Hide the previously visible one        
  });  

});

Here is a working jsbin sample

Upvotes: 0

Musa
Musa

Reputation: 97672

You can change the show method to toggle, so the clicked "id" will toggle and the other will hide if its visible

function toggleSig(divId) {
    $('.forum_signature').each(function(index) {
        if ($(this).attr("id") == divId) {
            $(this).toggle(200);
        }
        else {
            $(this).hide(600);
        }
    });
}

https://jsfiddle.net/4yg83kru/2/

Upvotes: 1

Related Questions