I have a header with 3 links, all linking to a specific div with a corresponding id:
Create new css class called BoxControl
consider this in all <a>
elements for trigger show/hide event.
Then Add .active
css class and add it to default class list of the element you want to show in first view as shown bellow.
Finally, implement JS as for your HTML structure tell that is your best option otherwise you'll have to modify your HTML.
Codepen Link
// Capture all elements of <a> output should be in an array
var box = document.getElementsByClassName("boxControl");
// Create new variable i stands for index to be used in for loop
var i;
// Loop through all elements been found in box variable
for (i = 0; i < box.length; i++) {
// Add Event Listener of Click for <a> elements found in the variable box
box[i].addEventListener("click", function(e) {
// Add e in callback function trace the element triggered this event
// In other words, which button has been clicked
var clicked =
e.target.getAttribute("href");
// Tricky bit: As per your request they should be at least
// one default active element otherwise or else will not remove any active class
if (document.querySelector(".active")) {
document.querySelector(".active").classList.remove("active");
// Use value of captured attribute (href) to target and toggle the new active class
document.querySelector(clicked).classList.toggle("active");
// Not found any active css class (box)
} else {
var clicked = e.target.getAttribute("href");
document.querySelector(clicked).classList.toggle("active");
}
})
};
body {
font-size:32px;
}
.links {
display:flex;
}
.links a {
padding:10px;
}
.active {
display:block!important;
}
#box1 {
background-color:crimson;
display: none;
}
#box2 {
background-color:darkgreen;
display: none;
}
#box3 {
background-color:gold;
display:none;
}
<div class="links">
<a href="#box1" class="boxControl">Box1</a>
<a href="#box2" class="boxControl">Box2</a>
<a href="#box3" class="boxControl">Box3</a>
</div>
<div class="box active" id="box1">Box1 content</div>
<div class="box" id="box2">Box2 content</div>
<div class="box" id="box3">Box3 content</div>
Follow below the snippet, hope your problem will fix with html and css,
body {
font-size: 32px;
}
.links {
display: flex;
a {
padding: 10px;
}
}
.box:not(:target) {
display: none;
}
#box1{
display: block;
}
#box2:target ~ #box1,
#box3:target ~ #box1{
display: none;
}
#box1 {
background-color: crimson;
}
#box2 {
background-color: darkgreen;
}
#box3 {
background-color: gold;
}
<div class="links">
<a href="#box1">Box1</a>
<a href="#box2">Box2</a>
<a href="#box3">Box3</a>
</div>
<div class="box" id="box2">Box2 content</div>
<div class="box" id="box3">Box3 content</div>
<div class="box" id="box1">Box1 content</div>
the box1 is default and when you trigger the box2, box3 you can see box1 will get display none. mainly it's working for "general sibling selector (~)"