Now You See Me, Now You toggle()


You can use jQuery’s toggle() method to toggle the visibility of an element. Here is a simple example:

$('#yourElementId').toggle();

This line of code will hide the element if it is currently visible and show it if it is currently hidden.

Here’s a more complete example with a button that toggles the visibility of a div:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#toggleButton").click(function(){
    $("#targetDiv").toggle();
  });
});
</script>
</head>
<body>

<button id="toggleButton">Toggle visibility</button>
<div id="targetDiv">This is a div.</div>

</body>
</html>

In this example, whenever the button with id “toggleButton” is clicked, the visibility of the div with id “targetDiv” will be toggled. If the div is currently visible, it will be hidden, and vice versa. The $(document).ready() function ensures that the entire HTML document is fully loaded before the script runs.