How to use CSS Visibility Property In Javascript
Make a card with the main heading, subheading, paragraph, and button. Give a specific style to all the elements. The JavaScript function togglelement()
is called when the user clicks the button. It gets the div element with the id myparagraph
. The toggleElement function switches the visibility of an element with the id ‘myparagraph’. It checks the current visibility style using “window.getComputedStyle” and toggles it, if hidden, it becomes visible, and vice versa. Refer to the visibility Article for the detailed description.
Example: Illustration of toggling between hiding and showing an element using visibility property.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> < style > @import url( 'https://fonts.googleapis.com/css2?family=Poppins&display=swap'); body { display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; font-family: 'Poppins', sans-serif; } .card { width: 300px; padding: 20px; text-align: center; border: 5px solid #1e4e2e; border-radius: 20px; } h2 { color: #257443; } h3 { color: blueviolet; } div { font-size: 20px; padding: 3px; font-weight: 700; color: rgb(22, 74, 39); background-color: rgb(227, 238, 227); } button { margin-top: 10px; padding: 8px; cursor: pointer; border-radius: 10px; background-color: #50aa72; color: white; font-size: 15px; } </ style > </ head > < body > < div class = "card" id = "myCard" > < h2 >w3wiki</ h2 > < h3 >Hiding and showing an element using Visibility property </ h3 > < div id = "myparagraph" > w3wiki </ div > < button onclick = "toggleElement()" > Click to Toggle Text </ button > </ div > < script > function toggleElement() { const paragraph = document .getElementById('myparagraph'); const currentVisibility = window .getComputedStyle(paragraph).visibility; if (currentVisibility === 'hidden') { paragraph.style.visibility = 'visible'; } else { paragraph.style.visibility = 'hidden'; } } </ script > </ body > </ html > |
Output:
How to Toggle between Hiding and Showing an Element using JavaScript ?
Toggle between hiding and showing an element using JavaScript provides the feature of efficient space usage by allowing users to hide content sections they may not need to minimize distractions, leading to a cleaner and more organized layout.
Contact Us