+ 1

How do you make an element disappear if button has been clicked? (NOT toggle)

I am creating a message center and need to filter by read and unread. How can I show or hide an element based on a condition in a function? Been using if else statement (i.e. (incorrect format here i know) if background color = #cccccc then hide, if not then show) but haven't had any luck no matter how I adjust the code. The function should show elements with white backgrounds and hide elements with color background. This will NOT be a toggle.

14th Jun 2023, 12:37 AM
Juanita
Juanita - avatar
3 Respuestas
+ 2
<div id="myElement" style="background-color: #cccccc;">This is the element to hide/show</div> <button onclick="hideElement()">Hide/Show Element</button> <script> function hideElement() { var element = document.getElementById("myElement"); if (element.style.backgroundColor === "rgb(204, 204, 204)") { element.style.display = "none"; } else { element.style.display = "block"; } } </script>
16th Jun 2023, 9:42 AM
Vaibhav
Vaibhav - avatar
0
To show or hide an element based on a condition when a button is clicked, you can use JavaScript and CSS. Here's an example of how you can achieve this: HTML: <button id="filterButton">Filter</button> <div class="message" style="background-color: #cccccc;">Read Message</div> <div class="message">Unread Message</div> CSS: .message { display: block; } .hide { display: none; } JavaScript: document.getElementById('filterButton').addEventListener('click', function() { var messages = document.getElementsByClassName('message'); for (var i = 0; i < messages.length; i++) { var message = messages[i]; if (message.style.backgroundColor === 'rgb(204, 204, 204)') { message.classList.add('hide'); } else { message.classList.remove('hide'); } } });
14th Jun 2023, 12:56 AM
Ramyar Doski
Ramyar Doski - avatar
0
In this example, the button with the id "filterButton" is assigned an event listener that listens for the click event. When the button is clicked, it iterates through all the elements with the class "message". If the background color of a message is #cccccc, it adds the "hide" class to hide the element. Otherwise, it removes the "hide" class to show the element. By default, all message elements are displayed, and the ones with a background color of #cccccc will be hidden when the button is clicked. This is achieved by applying the "hide" class, which sets the display property to "none".
14th Jun 2023, 12:57 AM
Ramyar Doski
Ramyar Doski - avatar