How to Create a Text Toggle with jQuery?

Estimated read time 1 min read

To create a text toggle with jQuery, you can use the toggle() method. Here’s an example code snippet:

HTML:

<p id="text">Click here to toggle the text</p>

jQuery:

$(document).ready(function() {
  $('#text').click(function() {
    $(this).toggle(function() {
      $(this).text('Show text');
    }, function() {
      $(this).text('Hide text');
    });
  });
});

Explanation:

  1. The $(document).ready() function ensures that the jQuery code is executed only after the page has finished loading.
  2. The $('#text').click() function specifies that when the element with the ID text is clicked, the following code is executed.
  3. The $(this).toggle() function toggles the element’s visibility.
  4. The first callback function in $(this).toggle() sets the text of the element to “Show text” when the element is hidden.
  5. The second callback function in $(this).toggle() sets the text of the element to “Hide text” when the element is visible.

When the user clicks the element with the ID text, it will toggle between the two text values “Show text” and “Hide text” and the visibility of the element will be toggled as well.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply