How to toggle hide and show with jquery?

by eric.hamill , in category: JavaScript , 2 years ago

How to toggle hide and show with jquery?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@eric.hamill You can use toggle() method in jQuery to hide and show text or element, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
</head>
<body>
<div>
    <p>Lorem ipsum dolor sit amet.</p>
    <button id="button">Hide and Show</button>
</div>
</body>
<script>
    $("#button").on('click', () => {
        $("p").toggle()
    })
</script>
</html>


Member

by devin , a year ago

@eric.hamill 

To toggle hide and show an element with jQuery, you can use the toggle() method. This method shows the element if it is hidden, and hides the element if it is visible.


Here's an example:


HTML:

1
2
<button id="myButton">Toggle</button>
<div id="myDiv">Hello World!</div>


JavaScript (with jQuery):

1
2
3
4
5
$(document).ready(function() {
  $("#myButton").click(function() {
    $("#myDiv").toggle();
  });
});


In this example, when the #myButton element is clicked, the #myDiv element is toggled (shown if it's hidden, hidden if it's shown).


You can also use the hide() and show() methods separately, if you want more control over when the element is hidden or shown. For example:

1
2
3
4
5
6
7
8
9
$(document).ready(function() {
  $("#myButton").click(function() {
    if ($("#myDiv").is(":hidden")) {
      $("#myDiv").show();
    } else {
      $("#myDiv").hide();
    }
  });
});


In this example, the #myDiv element is only shown when it's hidden, and hidden when it's shown.