How to show/hide multiple divs using if/else statement?
So let's walk through it in the first myFunction
. That will work reliably because there's only two options - "is x set to display: none
? if so, do X; otherwise, do Y" will always work as expected because it is simple binary logic (all the cases are handled, it basically just toggles the style.display
property). As soon as you bring more complicated logic into the equation and take multiple factors into consideration, it gets a little more slippery, and you need to formulate your approach more carefully.
The logic you basically want is, if X is hidden, show it; if y is hidden AND x is visible, show it; finally, if X is visible AND y is visible AND z is hidden, show it. You can write this in a really readable way by defining some quick isHidden()
, isVisible()
, and show()
helper functions:
EDIT: FZs made a good point about classes not being caught by this logic. To account for that, all we need to do is add an "OR classList
contains hidden
" expression to the isHidden()
check and voila.
// helperslet isHidden = (el) => el.style.display == "none" || el.classList.contains('hidden'), isVisible = (el) => !isHidden(el), show = (el) => el.style.display = "block";
// elementslet x = document.getElementById("div-x"), y = document.getElementById("div-y"), z = document.getElementById("div-z");
// click handlerlet handleClick = () => {
if (isHidden(x)) show(x);
else if (isHidden(y) && isVisible(x)) show(y);
else if (isHidden(z) && isVisible(y) && isVisible(x)) show(z);
else console.log("It worked!"); }
document.getElementById('btn').addEventListener('click', handleClick);
<div id="div-x" style="display:none">X</div><div id="div-y" style="display:none">Y</div><div id="div-z" style="display:none">Z</div>
<button id="btn">Click me!</button>
Show/Hide multiple Divs with same class name (javascript)
EDIT
@cirix has brought to my attention that my original code breaks because of the use of nextElementSibling
without the necessary precautions to terminate the sibling chain. As it was before the edit if the last div was clicked it nextElementSibling
would report a null since the last element would never have a next sibling (that's what makes last ...last).
There are 2 changes:
- Added an extra condition to ensure that the only
event.target
s dealt with are<a>
nchors, thereby fixing the issue. - Removed
classList.add/remove
and replaced them withclassList.toggle()
, that's an improvement, not a fix.
Use event delegation by wrapping all of your elements in one element. Then register the click event on it. With a little more setup you'll be able to control as many links as you want with just one eventListener. Details commented in Snippet.
SNIPPET
// Reference the parent elementvar main = document.getElementById('main');
/* Register main to the click event || when clicked ANYWHERE within main || toggle() is called*/main.addEventListener('click', toggle, false);
function toggle(e) { /* Determine if the current element in the || event chain is the anchor that was || clicked. */ if (e.target !== e.currentTarget && e.target.nodeName === "A") { /* tgt is the clicked link || txt is the div that follows tgt */ var tgt = e.target; var txt = tgt.nextElementSibling; // Toggle classes .on and .off txt.classList.toggle('on'); txt.classList.toggle('off'); }
}
.off { display: none;}
.on { display: inline-block;}
<section id='main'> <a class='toggleText' href="#/">Show1</a> <div class='displayText off'> Text1 </div> <a class='toggleText' href="#/">Show2</a> <div class='displayText off'> Text2 </div> <a class='toggleText' href="#/">Show3</a> <div class='displayText off'> Text3 </div> <a class='toggleText' href="#/">Show4</a> <div class='displayText off'> Text4 </div></section>
jQuery show / hide multiple divs
By default keep all .carDetails
div as hidden.
Keep open
class on first car div.
Remove/Add .open
class on the carDetails
that is clicked.
$(".carTitle").on('click', function(e) { var carDetailsDiv = $(event.currentTarget).next(); if ($(carDetailsDiv).hasClass('open')) { $(carDetailsDiv).removeClass('open'); } else { $(carDetailsDiv).addClass('open'); }
event.preventDefault(); return false;});
.carDetails { display: none;}
.carDetails.open { display: block;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="carItem01_container"> <div id="carToyota" class="carTitle"> <div class="carName">Toyote </div> </div> <div id="carToyota_show" class="carDetails open"> <div class="carDescription"> ... </div> </div></div>
<div id="carItem02_container"> <div id="carMazda" class="carTitle"> <div class="carName">Mazda </div> </div> <div id="carMazda_show" class="carDetails"> <div class="carDescription"> ... </div> </div></div>
<div id="carItem03_container"> <div id="carVolvo" class="carTitle"> <div class="carName">Volvo </div> </div> <div id="carVolvo_show" class="carDetails"> <div class="carDescription"> ... </div> </div></div>
Related Topics
Create a Newline for Every X Number of Characters
How to Detect Overflow of React Component Without Reactdom
Navigationduplicated Navigating to Current Location ("/Search") Is Not Allowed
Focus Next Input Once Reaching Maxlength Value
How to Add Spaces to for Loop Output in JavaScript
Javascript Add Class Active When Click a Link After Load Another Page
Barcode Scanner for Mobile Phone for Website in Form
Invalid Attempt to Spread Non-Iterable Instance
How to Implement Ping/Pong Request for Websocket Connection Alive in JavaScript
Multiply and Sum Input Values Created Dynamically in Jquery
How to Increment a Number After Every 1 Second Using JavaScript
Generate a Weighted Random Number
Get the Value of Datepicker on Change in Jquery
If Check Box Checked Disable Other, If Unchecked Enable All in React
Best Way to Get Objects With Highest Property Value
Chart.Js Showing Time (Hh:Mm:Ss - 24 Hour Clock) on Xaxis