Tuesday, 4 February 2020

Create buttons to hide/show text in jQuery

The following jQuery code is designed to have 2 buttons - 1 which hides the webpage text and the other which shows it again.
Screenshot of show/hide buttons
Screenshot of show/hide buttons
Each button has its own 'id' name depending on which task it will perform: show or hide. We use the '#id Selector' to target each id and use the 'click' method to either 'show/hide' all elements within a paragraph (<p>) tag.

<!DOCTYPE html>
<html>
<head>
<!-- add the latest version of jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// apply 'click' event to 'hidden' id
$("#hidden").click(function() {
// hide any text contained within a paragraph (p) tag, at a speed of 1 second
$("p").hide(1000);
});
// apply 'click' event to 'visible' id
$("#visible").click(function() {
// show any text contained within a paragraph (p) tag, at a speed of 1 second
$("p").show(1000);
});
});
</script>
</head>
<body>
<p>Text Paragraph 1</p>
<!-- 2 buttons to perform the necessary actions, with different id's -->
<button id="hidden">Hide</button>
<button id="visible">Show</button>
</body>
</html>
Create buttons to hide/show text in jQuery

No comments:

Post a Comment