Iām diving into the world of jQuery
and facing some challenges with the .toggle()
function.
My goal is to have multiple <div>
elements displayed in the same position, but only one visible at a time. When a new <div>
is opened, the previous one should automatically close.
Here's my current HTML setup:
$(document).ready(function() {
$("#button1").click(function() {
$("#box1").toggle(1000);
});
});
$(document).ready(function() {
$("#button2").click(function() {
$("#box2").toggle(1000);
});
});
.container {
width: 90px;
}
.box1 {
background-color: green;
color: red;
display: none;
}
.box2 {
background-color: blue;
color: yellow;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class=box1 id=box1>
This is Box 1
</div>
<div class=box2 id=box2>
This is Box 2
</div>
</div>
<a href="#" id="button1">Box1</a>
<a href="#" id="button2">Box2</a>
Furthermore, I believe that using just one toggle()
function instead of four would be more efficient for what I want to achieve. However, attempting to apply the same function across different IDs or classes isn't working as expected.
What am I overlooking or doing incorrectly in this scenario?