jessica
jessica

Reputation: 1687

Hiding and showing a div using jQuery

I have a div that is supposed to hide itself when clicked on. Then if you click on it again, it will show itself. Then if you click on it again, it will hide itself again, and so on and so forth.

When it's clicked on the first time, it checks to see if the variable $visible is true or not. If $visible is true, it'll hide it, and then set $visible to null. Else if $visible is not true, it'll show it, and then set $visible to true. But for some reason it'll not doing that at all.

I'm sure I did something wrong, so please take a look at my code:

<div id="id">Hello</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
  //*************************************************************
  function hideOnClick($id) {
    $("#" + $id).click(function() {
      $(this).hide();
    });
  }

  function showOnClick($id) {
    $("#" + $id).click(function() {
      $(this).show();
    });
  }

  //*************************************************************

  $(document).ready(function() {
    $id = "id";
    $visible = "true";

    $("#" + $id).click(function() {
      if ($visible == "true") {
        hideOnClick($id);
        $visible = null;
      } else {
        showOnClick($id);
        $visible = "true";
      }
    }); //end of $("#"+$id).click(function()      
  }); //end of $(document).ready(function()

  //*************************************************************
</script>

Results:

First click on div #id: Nothing happens.
Second click on div #id: #id hides itself
Third click on div #id: Nothing happens. Doesn't show itself again.
Fourth click on div #id: Nothing happens. Doesn't show itself again.
Fifth click on div #id: Nothing happens. Doesn't show itself again.
And this continues on indefinitely...

Upvotes: 0

Views: 2503

Answers (3)

Vance
Vance

Reputation: 897

You can also do that without creating a button:

    $(":not(#div)").click(function(){$('#div').show();});

instead of:

    $("#div").click(function(){$('#div').show();});

hide part:

     $("#div").click(function(){$(this).hide();});

Upvotes: 1

user2707389
user2707389

Reputation: 827

You can use jQuery's toggle class:

 $("#myID").click(function(){
        $("#myID").toggleClass("visible");
    });

Assuming you have a class called visible:

.visible{
  visibility: hidden;
}

Upvotes: 1

Buzinas
Buzinas

Reputation: 11725

Firstly, let me say that jQuery already has a feature for that, named .toggle.

Secondly, if you're hiding a div, it isn't anymore inside your page, so you won't be able to click it.

So, if you wanna do that, you'll need to use the CSS opacity: 0, or visibility: hidden. E.g:

$(this).css('visibility', 'hidden');  // to hide
$(this).css('visibility', 'visible'); // to show

Upvotes: 2

Related Questions