To hide, show or toggle a div in jquery is very easy as compared to the traditional ways in javascript;where we get the element by Id or name and use the css to show hide those elements.
Lets see some sample codes on How to show hide div using jquery.
A) Using show() and hide() functions
1. Create a HTML page
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html> <head> <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> <script type="text/javascript" src="showHideDiv.js"></script> </head> <body> <button onClick="showDiv()">Show Div</button> <button onClick="hideDiv()">Hide Div</button> <hr> <div id="showHideDiv" style="width:300px;background-color: #cecece; padding: 5px 10px;"> This content in the Div will be used to demo the Show Hide functions of JQuery </div> </body> </html> |
2. Add jquery functions
You can either add in the HTML or create a new js file.
1 2 3 4 5 6 7 8 9 10 |
$(document).ready(function(){ showDiv = function(){ $("#showHideDiv").show(); } hideDiv = function(){ $("#showHideDiv").hide(); } }); |
The Output will look like the below screenshot. When you click the Show Div button, the div will be displayed. When you click on Hide Div button, the div will be hidden.
B) Using toggle() function
To make things more easy, jquery provide a toggle function, which can be used to show/hide div.
Lets see a sample code.
1. HTML Code: the HTMl code will look almost same as above code. Only difference will be that we only have one button now.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <head> <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> <script type="text/javascript" src="showHideDiv.js"></script> </head> <body> <button onClick="showHideDiv()">Show/Hide Div</button> <hr> <div id="showHideDiv" style="width:300px;background-color: #cecece; padding: 5px 10px;"> This content in the Div will be used to demo the Show Hide functions of JQuery </div> </body> </html> |
2. jquery functions
Similar to HTML code, we will have only one jquery function now, that uses the toggle() function.
1 2 3 4 5 6 |
$(document).ready(function(){ showHideDiv = function(){ $("#showHideDiv").toggle(); } }); |
Output will look like this.