How to Make a DIV Visible and Invisible with JavaScript?
To swiftly show or hide a div, apply JavaScript's element.style.display
, setting it to 'none'
to make it disappear, or 'block'
to reveal it.
To toggle visibility, use your div's unique ID with the function toggleDivVisibility('divID')
.
Additional Techniques to Control Visibility
Making Space with visibility
The visibility
property aids the element to preserve its layout space even when it's invisible.
Unlike display: none
, which extracts the element from the document layout, visibility: hidden
conserves the element's space.
State Toggle Using HTML Attributes
By using the hidden
attribute to toggle visibility, less complexity and more semantic aspects come into play.
Retracing Back to Defaults with display: revert
To return to default styles, you can use 'revert' in CSS, reverting back to the user-agent's initial styles.
Though remember, 'revert' is well supported but not absolutely universal. Check for browser compatibility before sending it to production.
Dynamic Toggle Using Class Names
With class names, achieve a cleaner approach for separating concerns:
Introduce a .hidden
class in your stylesheet and toggle its state using this function, passing the desired class name.
Advanced Scenarios of Visibility Control
Keeping Accessibility in Mind
When handling dynamic visibility always remember accessibility. Invisible contents may still influence screen readers, so consider supporting them accordingly.
Boulevard to Responsive Visibility
Divs require different visibility depending upon screen size at times. Align your JavaScript methods with media queries in CSS for a proper responsive behavior.
Smooth as Butter with Animation and Transitions
Give your visibility toggles an aesthetic upgrade with CSS animations or transitions. Combine visibility toggling with an opacity transition to achieve a pleasant fading effect.
jQuery Orientation for Visibility
In case you're leveraging jQuery, manipulate visibility with the following methods:
A simpler syntax is an advantage here, but make sure you consider extra overheads before using jQuery for such fundamental operations.
Was this article helpful?