- JavaScript — How to show and hide div by a button click
- Learn JavaScript for Beginners 🔥
- About
- Search
- Tags
- How TO - Toggle Hide and Show
- Toggle (Hide/Show) an Element
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Using JavaScript to Show and Hide a Div
- Using JavaScript to Show/Hide a Div With a Click
- Скрыть / показать элементы JavaScript
- Используйте свойство style.visibility , чтобы скрыть / показать элементы HTML
- Используйте свойство style.display , чтобы скрыть / показать элементы HTML
- Используйте jQuery hide() / show() , чтобы скрыть / показать элементы HTML
JavaScript — How to show and hide div by a button click
To display or hide a by a click, you can add the onclick event listener to the element.
The onclick listener for the button will have a function that will change the display attribute of the from the default value (which is block ) to none .
For example, suppose you have an HTML element as follows:
The element above is created to hide or show the element on click.
You need to add the onclick event listener to the element like this:
When you click the element again, the display attribute will be set back to block , so the will be rendered back in the HTML page.
Since this solution is using JavaScript API native to the browser, you don’t need to install any JavaScript libraries like jQuery.
You can add the JavaScript code to your HTML tag using the tag as follows:
Feel free to use and modify the code above in your project.I hope this tutorial has been useful for you. 👍
Learn JavaScript for Beginners 🔥
Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.
A practical and fun way to learn JavaScript and build an application using Node.js.
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
How TO - Toggle Hide and Show
Toggle between hiding and showing an element with JavaScript.
Toggle (Hide/Show) an Element
Step 1) Add HTML:
Example
Step 2) Add JavaScript:
Example
function myFunction() <
var x = document.getElementById("myDIV");
if (x.style.display === "none") <
x.style.display = "block";
> else <
x.style.display = "none";
>
>Tip: For more information about Display and Visibility, read our CSS Display Tutorial.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
How to Hide and Show a
If you don’t know how to hide and show a element, you should definitely check this tutorial! Hiding and showing a in HTML is quite an easy thing. You can do it with CSS or a small piece of JavaScript and jQuery codes.
The document.getElementById will select the with given id. You should set the display to "none" so as to make it disappear when clicked on :
html> head> title>Title of the document title> style> div < width: 100px; height: 100px; float: left; margin-right: 50px; > .parallelogram < border-radius: 0; -moz-border-radius: 0; -webkit-border-radius: 0; margin-left: 20px; -webkit-transform: skew(20deg); -moz-transform: skew(20deg); -o-transform: skew(20deg); > .circle < border-radius: 50%; -moz-border-radius: 50%; -webkit-border-radius: 50%; > .square < border-radius: 0%; -moz-border-radius: 0%; -webkit-border-radius: 0%; > #parallelogram < background-color: #1c87c9; > #circle < background-color: #8ebf42; > #square < background-color: #cccccc; > style> head> body> h2>Click on the figure h2> div class="parallelogram" id="parallelogram"> div> div class="circle" id="circle"> div> div class="square" id="square"> div> script> document.getElementById("parallelogram").onclick = function( ) < document.getElementById("parallelogram").style.display = "none"; > document.getElementById("circle").onclick = function( ) < document.getElementById("circle").style.display = "none"; > document.getElementById("square").onclick = function( ) < document.getElementById("square").style.display = "none"; > script> body> html>html>
Another example of hiding and showing div with JavaScript:
html> html> head> title>Title of the document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> style> p < padding: 20px; background: blue; > style> head> body> button type="button" class="toggle-btn">Toggle button> p>Lorem Ipsum is simply dummy text. p> script> $(document).ready(function( ) < // Display alert message after toggle paragraphs $(".toggle-btn").click(function( ) < $("p").toggle(2000, function( ) < // Code to be executed alert("The toggle effect is completed."); >); >); >); script> body> html>
Now let’s see how you can hide and show your element with pure CSS using the CSS :hover pseudo-class. Here’s the full code:
html> html> head> title>Title of the document title> style> form < display: none; > .example:hover>form < display: block; > style> head> body> div class="example"> div>Hover to show the form div> form action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=alexcican', 'popupwindow', 'scrollbars=yes,width=650,height=620');return true"> p> input type="text" class="email_field" name="email" size="30" value="E-mail address" /> input type="hidden" value="alexcican" name="uri" /> input type="hidden" name="loc" value="en_US" /> input class="email_btn" name="submit" type="submit" value="Done"/> p> form> div> body> html>
When the user hovers over the , it disappears, and the form is displayed.
Using JavaScript to Show and Hide a Div
We can use JavaScript to show and hide a div using one button by combing the getElementById() method, the display property, and an if else conditional statement.
var displayStatus = document.getElementById("someDiv"); if ( displayStatus.style.display == 'none' ) < displayStatus.style.display = 'block'; >else
We can use JavaScript to show a div and hide a div, but to be able to toggle between the two, we can do so using the code above.
Let’s say we have the following html:
If we want to use JavaScript to show hide the div, we can do so by targeting the element’s display property. We do this simply by getting the id of the div and then changing its display property to “block” if it is hidden, or “none” if it is shown. We check this with an if-else conditional statement.
var displayStatus = document.getElementById("div1"); if ( displayStatus.style.display == 'none' ) < displayStatus.style.display = 'block'; >else
Note that we can also show/hide (or toggle) a div easily using jQuery with the toggle() method.
Using JavaScript to Show/Hide a Div With a Click
We can use JavaScript to show/hide a div very easily by combining the display property and an if-else conditional statement with an onclick event.
Let’s say that we have the following HTML where we want to give the user the ability to show and hide the div #div1. The div will just be a greenish box that will be shown to start.
In the JavaScript code, we will add an onclick event to a button that will run a function we will create. In the function, we will simply change the display property of the div to “block” if it is hidden, or “none” if it is shown.
Here is the JavaScript code:
The final code and output for this example of using JavaScript to show/hide a div with a click is below:
Скрыть / показать элементы JavaScript
- Используйте свойство style.visibility , чтобы скрыть / показать элементы HTML
- Используйте свойство style.display , чтобы скрыть / показать элементы HTML
- Используйте jQuery hide() / show() , чтобы скрыть / показать элементы HTML
- Используйте jQuery toggle() , чтобы скрыть / показать элементы HTML
- Используйте addClass() / removeClass() , чтобы скрыть / показать элементы HTML
Мы часто сталкиваемся с ситуациями, когда мы хотим переключиться между отображением и скрытием элемента. В этом руководстве рассказывается, как скрыть / отобразить элемент в JavaScript.
Используйте свойство style.visibility , чтобы скрыть / показать элементы HTML
Свойство style.visibility , когда установлено значение hidden, делает целевой элемент скрытым, но не удаляет его из потока. Итак, целевой элемент отображается, но не отображается. Это не влияет на планировку и позволяет другим элементам занимать свое естественное пространство. Мы можем снова сделать целевой элемент видимым, вернув для свойства значение visible .
document.getElementById(id).style.visibility = "visible"; // show document.getElementById(id).style.visibility = "hidden"; // hide
Используйте свойство style.display , чтобы скрыть / показать элементы HTML
Свойство style.display , когда установлено в none , удаляет целевой элемент из обычного потока страницы и позволяет остальным элементам занимать его пространство. Хотя целевой элемент не отображается на странице, мы все равно можем взаимодействовать с ним через DOM. Затрагиваются все потомки, и они не отображаются так же, как родительский элемент. Мы можем снова сделать целевой элемент видимым, установив для свойства значение block . Желательно установить display как '' , потому что block добавляет поле к элементу.
document.getElementById(id).style.display = 'none'; // hide document.getElementById(id).style.display = ''; // show
Используйте jQuery hide() / show() , чтобы скрыть / показать элементы HTML
- Скорость : определяет скорость задержки эффекта затухания.
- Замедление : определяет функцию замедления, используемую для перехода в видимое / скрытое состояние. Принимает два разных значения: свинг и линейный .
- Обратный вызов : это функция, выполняемая после завершения выполнения метода show() .
Точно так же метод jQuery hide() помогает скрыть выбранные элементы. Принимает те же 3 параметра, что и show() .
$("#element").hide(); // hide $("#element").show(); // show