Dominicanstan
Dominicanstan

Reputation: 205

How to make a jQuery Toggle?

I'm using this: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_toggle

the thing here is that i change the button to an transparent image. and i want the image to change when the the <div> is hidden.

for example: The image is a arrow pointing down (when i click the arrow i want the image to disappear) and i want a new image pointing up to show the <div>.

If you dont understand i have a image here: enter image description here that's what is happening now; you see that even when my div is hidden it show the "hide div button".

In the image below you can see what i want! I want the image to chane when the is hidden to "show div".

Remenber that the image is .png

enter image description here

Upvotes: 1

Views: 230

Answers (3)

Shawn31313
Shawn31313

Reputation: 6052

You can just use an toogle from one of the effects like fade and slide.

Like this:

$('#me').click(function() {
    var f = $('#pan').is(':hidden') ? 'show' : 'hide';
    if (f == 'hide') {
        $('#pan').slideUp();
        $(this).html('Show ▼');
    }
    if (f == 'show') {
        $('#pan').slideDown();
        $(this).html('Hide ▲');
    }
});

See how it works

I personally don't like the toggle function, so I kind of just make my own. I know you want to use an image, but you can still do this with a little change in the code.

Upvotes: 3

Purag
Purag

Reputation: 17071

To save on some code, you could use this:

$("button").toggle(function(){
   $("div").show();
   $(this).html("Hide div.");
}, function(){
   $("div").hide();
   $(this).html("Show div.");
});

Example.

Upvotes: 0

IvoryCirrus
IvoryCirrus

Reputation: 622

I'm editing the example code of w3cschool website.

see below.

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").toggle();
    if($("p").css('display')=='none')
    {
      $(this).html('Show!!');
    }
    else
    {
      $(this).html('Hide!!');
    }
  });
});
</script>
</head>
<body>

<button>Hide!!</button>
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</body>
</html>

Upvotes: 1

Related Questions