Show/hide 'div' using JavaScript
Easily toggle a div
element's visibility using JavaScript's style.display
property:
Link it with an HTML trigger:
The function toggleDiv()
can swap the div
visibility.
Extending functionality and clever hacks
Dealing with varying display values
Use the getComputedStyle method to cater to elements with display values that are neither 'none' nor 'block':
Here, the element reverts to its original display style from the CSS stylesheet when it's not 'none'.
CSS is here to save the day
Get back inline to default CSS by removing the style.display
property:
Handing back control to CSS, rather than specifying 'block', assists with responsive designs.
Kicking it up a notch with custom-display
For extra control, pass the desired display property as an argument:
Stylin' with CSS classes
Toggle visibility with classes:
Toggle these classes in JavaScript for clean visual presentation:
Emphasizing style over syntax!
Keyboard warriors unite
Use Event Listeners instead of inline onclick
events; cleaner HTML, anyone?
Cut the jibber-jabber with jQuery
A little sprinkle of jQuery eases and simplifies:
Pitfalls and workarounds
Naturally, dealing with non-standard display values
When a div
uses display values other than 'block', like 'flex' or 'grid', modify the toggle function:
Remember to store the initial display value using data attributes for consistency:
Treating your users with style (transitions)
Use CSS transitions or JavaScript animations for smoother and more appealing visibility toggles.
Multiple elements? No problem!
Ensure your toggling function addresses the correct div
when dealing with multiple elements. Maintain unique identifiers and validate your selectors:
Was this article helpful?