jQuery

jQuery Hide and Show Element Example

Hello readers, today we will look into two useful jQuery methods that developers can use to hide an HTML element or to show any hidden HTML element. In this basic example, developers will learn how to hide or show an HTML element using the jQuery library.

1. Introduction

jQuery is nothing but a JavaScript library that comes with the rich functionalities. It’s small and faster than many JavaScript code written by an average web developer. By using jQuery developers can write less code and do more things, it makes the web developer’s task very easy. In simple word, jQuery is a collection of several useful methods, which can be used to carry out many common tasks in JavaScript. A couple of lines of jQuery code can do things which need too many JavaScript lines to do. The true power of jQuery comes from its CSS-like selector, which allows it to select any element from DOM and change, update or manipulate it. Developers can use jQuery to do cool animations like fade in or fade out. They can also change the CSS class of a component dynamically e.g. making a component active or inactive. I have used this technique to make tabbed UI in HTML. I can vouch for jQuery that once developers start using it, they will never go back to plain old JavaScript as jQuery is clear, concise, and powerful.

1.1 jQuery hide() Method

jQuery hide() method is used to hide the HTML elements. The element will not be displayed until the show() method is called for that element. This method is similar to display: none in CSS. Developers can use the hide() method in many ways.

  • hide(): This method hides the selected HTML element and this jQuery method doesn’t take any arguments. In other words, this method simply sets the inline-style to display: none for the selected elements
  • hide(speed): The argument speed determines the duration of this effect
  • hide(speed, callback): The speed argument determines the duration of this effect. String values like slow, fast, and the numeric value in milliseconds is normally used. With the callback argument, developers can specify what to do after the hide() method is called

1.2 jQuery show() Method

jQuery show() method is used to display the hidden HTML elements. The show() method restores the display properties of the matched set of elements to whatever they initially were i.e. typically block, inline, or inline-block. This method works on elements hidden with display: none in CSS. Developers can use the show() method in many ways.

  • show(): This method displays the selected HTML element and this jQuery method doesn’t take any arguments. In other words, this method simply sets the inline-style to display: none for the selected elements
  • show(speed): The argument speed determines the duration of this effect
  • speed(speed, callback): The speed argument determines the duration of this effect. String values like slow, fast, and the numeric value in milliseconds is normally used. With the callback argument, developers can specify what to do after the show() method is called

Do note, the default speed or duration string fast indicates the duration of 200ms, while the string slow indicates the duration of 600ms. If this parameter is omitted, the default 400ms is applied to the hide() and show() jQuery methods.

These new APIs make developer’s life easier, really! But it would be difficult for a beginner to understand this without an example. Therefore, let me show you how to hide and show the selected HTML elements using the jQuery library.

2. jQuery Hide and Show Elements Example

Here is a step-by-step guide for demonstrating the hide and show effects using jQuery.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure if you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will show on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 4: Archetype Selection
Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jQueryShowHide</groupId>
	<artifactId>jQueryShowHide</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

Let’s start building the application!

3. Application Building

Let’s create a basic application to understand the building blocks of this tutorial.

3.1 Load the jQuery Library

Since it is a pure JavaScript framework, so developers should add its reference using the <script> tag.

<script type="text/javascript" src="resource/js/jquery-3.2.1.min.js"></script>

Developers can either download the jQuery from the official website and the application will then directly load the jQuery library from the local drive or they can also include the direct CDN link under the script tag.

3.2 Define the Application

Next, we will define the sample application using the HTML tags.

<div id="buttons" align="center">
    <button type="button" id="hide-btn" class="btn btn-default">Hide Paragraphs</button>
    <button type="button" id="show-btn" class="btn btn-default">Show Paragraphs</button>
</div>

<div id="pText" align="center">
    <p>This is a paragraph!</p>
    <div> </div>
    <p>This is another paragraph!</p>
</div>

3.3 Define a jQuery Function

In this step, we’ll define a simple jQuery function to hide or show the paragraph text on a button click. Here $() is the default syntax for the jQuery function and is used to define jQuery part. $(document).ready method gets called when the document is loaded.

showHide.js

$(document).ready(function() {
	
    // Hide Displayed Paragraphs
    $("#hide-btn").click(function() {
        $("p").hide();
    });

    // Show Hidden Paragraphs
    $("#show-btn").click(function() {
        $("p").show();
    });
});

3.4 First jQuery Application

Complete all the above steps and save the file. Let’s see the sample code snippet.

index.jsp

<!DOCTYPE html>
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Example of jQuery Show Hide Effects</title>
	
	    <!-- Javascript Files -->
	    <script type="text/javascript" src="resource/js/jquery-3.2.1.min.js"></script>
	    <script type="text/javascript" src="resource/js/showHide.js"></script>
	
	    <!-- Bootstrap Css -->
	    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	
	    <style type="text/css">
	        p {
	        	width: 550px;
	            padding: 15px;
	            background: #F0E68C;
	        }
	        
	        .mt-25 {
	        	margin-top: 25px;
	        }
	    </style>
	</head>
	<body>
	    <h2 align="center" class="text-primary">jQuery Show Hide Example</h2>
	    <div id="container" class="text-center mt-25">
	    	 <div id="buttons" align="center" >
	            <button type="button" id="hide-btn" class="btn btn-default">Hide Paragraphs</button>
	            <button type="button" id="show-btn" class="btn btn-default">Show Paragraphs</button>
	        </div>
	        <div> </div>
	        <div id="pText" align="center" >
	            <p>This is a paragraph!</p>
	            <div> </div>
	            <p>This is another paragraph!</p>
	        </div>	       
	    </div>
	</body>
</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 6: How to Deploy Application on Tomcat
Fig. 6: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output (i.e. the welcome) page will be displayed.

http://localhost:8085/jQueryShowHide/

Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 7: Welcome Page
Fig. 7: Welcome Page

On clicking the Hide Paragraphs button, we will see that the paragraph text gets hidden.

Fig. 8: Hide Paragraph Text
Fig. 8: Hide Paragraph Text

Now, on clicking the Show Paragraphs button, we will see that the paragraph text is no more hidden and the text is again displayed on the web-page as shown in Fig. 7.

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to create a simple application where we have two buttons to hide and show the selected HTML elements. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.

7. Download the Eclipse Project

This was an example of jQuery hide() and show() methods for the beginners.

Download
You can download the full source code of this example here: jQueryShowHide

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button