简体   繁体   中英

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>

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...

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 . Eg:

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

You can use jQuery's toggle class:

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

Assuming you have a class called visible:

.visible{
  visibility: hidden;
}

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();});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM