My current challenge involves a JavaScript function that manipulates boxes by toggling classnames. The strange issue I'm facing is that the correct classes are being set at the correct times, but the div keeps alternating between the original class and the new one every second. I'll include the fiddle link for reference. On the webpage, there are four boxes. Clicking on one box successfully moves the other three to the left and expands the selected box. This functionality works perfectly. However, the problem arises when I click on a left box while one of the four boxes is already expanded. The expanded box starts transitioning to the new class but then reverts back to its expanded position, creating a never-ending back-and-forth movement. I've attempted to clear all classes from the div before translating, but it seems like there's a fundamental JavaScript concept I'm overlooking. None of my attempts have resolved the class conflict.
Website Markup:
<section id="content">
<div id="firstBox" class="firstBox" onclick="firstBoxController()">
2000-2005
</div>
<div id="secondBox" class="secondBox" onclick="secondBoxController()">
2005-2010
</div>
<div id="thirdBox" class="thirdBox" onclick="thirdBoxController()">
2010-2015
</div>
<div id="fourthBox" class="fourthBox" onclick="fourthBoxController()">
2015-2020
</div>
<div id="firstSub" class="hidden"></div>
<div id="secondSub" class="hidden"></div>
<div id="thirdSub" class="hidden"></div>
<div id="fourthSub" class="hidden"></div>
</section>
JS:
// Variable declarations
var first = document.getElementById("firstBox");
var firstSub = document.getElementById("firstSub");
var second = document.getElementById("secondBox");
var secondSub = document.getElementById("secondSub");
var third = document.getElementById("thirdBox");
var thirdSub = document.getElementById("thirdSub");
var fourth = document.getElementById("fourthBox");
var fourthSub = document.getElementById("fourthSub");
// Movement Functions
function firstLeft() {
first.className = "firstLeft";
}
function firstExpand() {
first.className = "expand";
firstSub.className = "translateRight";
}
// Controller Functions
function firstBoxController() {
if (first.classList.contains("firstBox")) {
secondLeft();
thirdLeft();
fourthLeft();
}
// More code for other scenarios
}
// More functions and code as described earlier
CSS:
.firstBox, .secondBox,
.thirdBox, .fourthBox {
/* CSS styling for the boxes */
}
// More CSS styles for the classes mentioned