How to Show an HTML Element with jQuery



JQuery


In this article, we detail how to show an HTML element with jQuery.

So, elements on a web page may be hidden by default. These are elements that do not need to be shown when a web page is first loaded. An example of this is a comment box for a reply to a comment. A visitor may go to a page where s/he can comment. However, the visitor may not choose to comment. Therefore, we would now show the reply comment boxes for all comments by default, only if the user wants to comment. Therefore, we would hide the reply comment boxes by default and only show them if a user clicks the comment button.

So jQuery has a built-in show() function, which will show an element or elements based on the code.

In this example, we will create a button that has an id of writecomment. When this button is clicked, a reply comment box will be shown, in which a user can write a comment. You can demo this below.




So we have a button that has the word, Comment.

Below this we have a div tag which contains an HTML textarea, along with some buttons underneath, simulating a reply commentbox.

This div tag, which has an id of "commentbox" is not shown by default when the page is loaded. The line, style="display:none" makes this div tag hidden by default.

Below is the HTML code for this button.



So now we will go to the jQuery code that allows this comment reply box to be shown when the Comment button is clicked.



So now we go over this code.

So at the top of the code, you must always import your jQuery code, so that jQuery can work. In the above example, we use the google CDN to allow jQuery to work on our page.

After this, we have our jQuery code.

The first thing you must always put in jQuery code is $(function() { });

This line says that whenever the page has fully loaded, then run this code. Without this, the jQuery code will not work.

Since we gave our button an id of 'writecomment', then we have, $('#writecomment'), to identify this button.

# identifies ids, while . identifies classes.

The rule of thumb is that ids are given to represent individual elements, while classes are used to represent groups of elements.

What we want to do in this code is that when the button is clicked, we show the div tag with an id of 'commentbox'. So we use the jQuery click event handler to listen for clicks.

Once a click occurs on this element, then we show the div tag using the jQuery show() function.

So if you demo the button above, you will see that it creates a reply commentbox.

And this is how you can show an HTML element with jQuery.


Related Resources

How to Hide an HTML Element with jQuery

How to Create a Comment System in Which Only One Reply Comment Box Can Be Open At Once with jQuery

How to Upload a File with the Click of an Image with jQuery



HTML Comment Box is loading comments...