Hiding and showing HTML elements is a common requirement in web development, and JavaScript provides several ways to achieve this. In this tutorial, we will explore how to hide and show HTML elements using JavaScript.
Understanding the display
Property
The display
property is used to specify the display type of an element. To hide an element, you can set its display
property to 'none'
. To show an element, you can set its display
property to a value such as 'block'
, 'inline'
, or 'inline-block'
.
// Hide an element
element.style.display = 'none';
// Show an element
element.style.display = 'block';
Hiding and Showing Elements using Functions
To make the code more reusable, you can create functions to hide and show elements. Here is an example:
function hide(element) {
element.style.display = 'none';
}
function show(element) {
element.style.display = '';
var computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');
if (computedDisplay === 'none') {
element.style.display = 'block';
}
}
You can use these functions to hide and show elements like this:
var element = document.getElementById('myElement');
hide(element);
show(element);
Toggling the Display of Elements
To toggle the display of an element, you can create a function that checks the current display state of the element and sets it to the opposite state.
function toggleDisplay(element) {
var computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');
if (computedDisplay === 'none') {
element.style.display = '';
if (window.getComputedStyle(element, null).getPropertyValue('display') === 'none') {
element.style.display = 'block';
}
} else {
element.style.display = 'none';
}
}
You can use this function to toggle the display of an element like this:
var element = document.getElementById('myElement');
toggleDisplay(element);
Using jQuery
If you are using jQuery, you can use its hide()
and show()
methods to hide and show elements.
$('#myElement').hide();
$('#myElement').show();
You can also use the toggle()
method to toggle the display of an element.
$('#myElement').toggle();
Best Practices
When hiding and showing elements, it’s a good practice to consider accessibility. You should ensure that the hidden elements are not focusable by setting their tabindex
property to -1
. You should also use ARIA attributes to provide a clear indication of the element’s state.
element.setAttribute('aria-hidden', 'true');
By following these best practices and using the techniques described in this tutorial, you can effectively hide and show HTML elements with JavaScript.