Showing and hiding content on a web page can add interactivity and provide a better user experience. With Jquery, a popular JavaScript library, this task becomes easier to accomplish. In this article, we'll go over the steps to show and hide divs on a button click with Jquery.
First, let's create a simple HTML page with two divs and a button. The first div contains some content and the second div is empty. The button will be used to toggle the visibility of the second div. Here is the code for the HTML page,
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div2").toggle();
});
});
</script>
</head>
<body>
<div id="div1">
<p>Some content</p>
</div>
<div id="div2" style="display:none;">
<p>Hidden content</p>
</div>
<button>Toggle</button>
</body>
</html>
In the head section of the HTML page, we first include the Jquery library and then add a script that uses the .ready()
function to execute the code when the page is fully loaded. The code inside the function sets up a click event for the button element using the .click()
function. The toggle()
function is used to show or hide the div with the id "div2". The div is initially hidden by setting the display
property to "none" in the style attribute of the div element.
When the button is clicked, the toggle()
function will show the div if it is hidden, and hide it if it is visible. The Jquery code makes it easy to show and hide the div with a simple button click.
In conclusion, Jquery provides a convenient way to show and hide content on a web page based on user interaction. The toggle()
function is a simple and effective solution for this task. With just a few lines of code, you can create dynamic and interactive web pages that provide a better user experience.