Hide a div container with JavaScript/jQuery
This post will discuss how to hide a div container in JavaScript and jQuery.
1. Using jQuery
The most common approach to hide an element in jQuery is to use the .hide() method. It works by setting the display CSS property to none. Now the document is rendered as though the element did not exist.
|
1 2 3 |
$(document).ready(function() { $('#container').hide(); }); |
Alternatively, you can directly set the display CSS property to none by calling .css("display", "none").
|
1 2 3 |
$(document).ready(function() { $('#container').css('display', 'none'); }); |
If you want to preserve the space taken by the element within the document, set the visibility property to hidden instead.
|
1 2 3 |
$(document).ready(function() { $('#container').css('visibility', 'hidden'); }); |
Another approach is to use the .fadeOut() method to set the display style property to none. You can further add a delay with the .delay() method.
|
1 2 3 |
$(document).ready(function() { $('#container').delay(1000).fadeOut('fast'); }); |
Like .fadeOut() method, you can use the .slideUp() method to set the display style property to none.
|
1 2 3 |
$(document).ready(function() { $('#container').slideUp(); }); |
2. Using JavaScript
In plain JavaScript, you can set the CSS display property to none, as shown below:
|
1 |
document.getElementById('container').style.display = "none"; |
The display property hides the element and also removes it from the DOM. To avoid changing the document’s layout, you can set its visibility to hidden instead.
|
1 |
document.getElementById('container').style.visibility = "hidden"; |
That’s all about hiding a div container in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)