jQuery Method How to - Use toggle() to show and hide element








Question

We would like to know how to use toggle() to show and hide element.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--  w w  w . j  ava2s .c o  m-->
  $(document).ready(function () {
        $("#needle").click(function () {
            $("#leftmenu").toggle();
        });   
    });
});
</script>
</head>
<body>
  <div id="container">
    <div id="leftmenu">left menu content</div>
    <div id="needle">click here</div>
  </div>
</body>
</html>

The code above is rendered as follows: