Javascript is responsible for causing a div to become stuck in a loop of alternating between

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

Check out the JSFiddle demo

Answer №1

To achieve the desired functionality, consider replacing the setInterval method with setTimeout. You can view a demonstration of this change in action on this Fiddle. By using setTimeout, your functions will only be executed once instead of being repeatedly called every second.

However, there are further opportunities to enhance your code.

UPDATE

You may be able to simplify your code by following this example. See the demo on Fiddle

function moveLeft() {
    this.el.className = "left";
}

function expand() {
    this.el.className = "expand";
    this.elSub.className = "translateRight";
}

var obj = {
    "first": {
        "el": document.getElementById("first"),
        "elSub": document.getElementById("firstSub")
    }
    , "second": {
        "el": document.getElementById("second"),
        "elSub": document.getElementById("secondSub")
    }
    , "third": {
        "el": document.getElementById("third"),
        "elSub": document.getElementById("thirdSub")
    }
    , "fourth": {
        "el": document.getElementById("fourth"),
        "elSub": document.getElementById("fourthSub")
    }
}


//functions for movement
function boxController(el) {

    for (var key in obj) {
        if (el.id != key) {
            if (obj[key].el.className === "expand") {
                obj[key].el.className = "center";
                window.setTimeout(
                    function(o) { return function() { moveLeft.call(o) }; }(obj[key]),
                  1000
               );  
                obj[key].elSub.className = "hidden";
            } else {
                moveLeft.call(obj[key]);
            }
        }
    }

    window.setTimeout( function(o) { expand.call(obj[el.id]) }, 1000);     

}

And here is the markup:

<section id="content">

    <div id="first" class="box" onclick="boxController(this)">1 2000-2005</div>
    <div id="second" class="box" onclick="boxController(this)">2 2005-2010</div>
    <div id="third" class="box" onclick="boxController(this)">3 2010-2015</div>
    <div id="fourth" class="box" onclick="boxController(this)">4 2015-2020</div>

    <div id="firstSub" class="hidden">1</div>
    <div id="secondSub" class="hidden">2</div>
    <div id="thirdSub" class="hidden">3</div>
    <div id="fourthSub" class="hidden">4</div>

</section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to transfer data from the parent component to child components, the data is appearing as undefined in the display

I have been working on passing data from a parent component to child components, but I keep encountering an issue where the data is showing as undefined. Below is the code snippet: Parent Component In this section, I have declared the variable part_data ...

Exploring the Functionality of Cookies in Nuxt 3 API Endpoints and Middlewares

Can cookies be utilized on the server side in Nuxt 3? For instance, I need to set a cookie in an API and then access its data in middleware: // ~/server/api/testApi.ts export default defineEventHandler(event => { /* setCookie('myCookie', ...

Is it possible to identify if an array is a polygon or multipolygon by examining its GeoJson data?

Recently, I came across an example illustrating a simple polygon. However, I wanted to display countries with complex polygons (multipolygons for some countries). Let me demonstrate the process: Example: "type": "Feature", "properties": { "Na ...

Can Microsoft Bot Framework chat window support rounded border corners?

Is it possible to style border corners in the Microsoft bot framework? I've attempted the following: const styleSet = window.WebChat.createStyleSet({ botAvatarImage: '/assets/logo.png', bubbleBackground: ...

What is the best way for me to collect messages submitted through a form on my website?

After completing my website using HTML, CSS, and JavaScript, I added a form with inputs for name, email, and message at the bottom of the page. Now, I am trying to figure out how to receive the information submitted by visitors in my email. ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Differences between JavaScript's window.onload and body.onload functionsWhen

My inquiry is similar yet slightly distinct from the one queried here: window.onload vs <body onload=""/> The comparison in that prior query was between utilizing window.onload and inline js. My question pertains to the disparity between ...

Error: Module 'config' not found by Jest

I have encountered an issue while using Jest to test my api calls file. When running a simple test, I received an error Cannot find module 'config' from 'api.service.js'. This error is related to the import statement at the top of my ap ...

Web Components Vanish Without Warning

I attempted to insert the HTML code for a button into my main index.html file after a specific line, but I encountered a strange issue. While the button displayed correctly, the homepage of my website suddenly vanished without any explanation. Here is the ...

Using VueJS to determine if a certain string includes a specific substring within an if-statement embedded within a v

I am aiming to verify if the link in a json object contains 'http'. If it does, I want to assign a target='_blank' attribute to the v-btn. The link could also be something like #test. Currently, this is how I am attempting to achieve i ...

Looking to eliminate the vertical spacing of the <hr> tag?

Summary: For a quick solution, just click on the image at the bottom. Greetings to everyone! I am facing an issue with two <div> elements that I need to separate using a <hr class="separator"> element. Below is the CSS code for the ...

Choosing HTML components using Selenium in the Whatsapp application

Apologies in advance for any language errors. I am currently working on a script using selenium and python to identify all messages with photos in a group. The structure of all message boxes is the same. Repository: # feel free to check out my code if you ...

Leveraging VueJS 2.0 server-side rendering: Maximizing data retrieval efficiency with preFetch and beforeRouteEnter techniques

Exploring VueJS server-side rendering and troubleshooting some issues. Using the latest VueJS Hackernews 2.0 as a starting point for this project. Currently facing an obstacle: The server fetches data using the preFetch method. All seems well. When a use ...

I am experiencing issues with my images not appearing on my Laravel website despite trying various solutions found online. The images upload successfully but fail to display on the site

I'm facing an issue where the image uploads correctly but does not display. Is there something missing in my code? <div class="col-md-4"> <img class="img img-fluid img-thumbnail" src="/storage/profile_images/{{$prof ...

Assess html code for Strings that include <% %> tags along with embedded scripts

Having a small issue with my code where I am receiving an HTML response from a web service as a java String. I need to display this String as HTML on my webpage, but the problem is that there are some script tags in the form of <% ... %> which are sh ...

Is there a way to create a dropdown menu that appears to emerge from behind a button?

I am struggling with the stack order of my dropdown menu. Despite using z-index, it appears in front of the button instead of behind it. I want it to look like it is coming out from behind the button. Here is my code: .subnav-wrapper { position: relat ...

Leveraging jQuery functions with dynamically generated DOM elements in JavaScript

On my website, I have a button that dynamically generates a dropdown menu, a textfield, and two buttons when clicked. The purpose of the textfield is to track the quantity selected, while the two buttons allow users to increase or decrease the value by 1. ...

Express application encountering an issue when trying to render a live chart with flot in the Jade client

Encountering an issue while trying to visualize real-time data using a flot chart. The client code displays the following error: Uncaught Invalid dimensions for plot, width = 1584, height = 0 I am perplexed by the fact that the height is showing as 0. ...

Using TypeScript to call Node.js functions instead of the standard way

Can someone assist me with the issue I'm facing? I have developed a default node.js app with express using Visual Studio nodejs tools, and now I am attempting to call the setTimeout function that is declared in node.d.ts. The code snippet in question ...

Unchecking the select-all checkbox in Ag-Grid after updating the row data using an external button

In my ag-grid setup, I have implemented checkboxes in the first row to allow users to select individual rows. Additionally, there is a "select all" checkbox in the header for easy selection of all rows with a single click. To create the select all checkbox ...