How can I implement a while loop for this animation using Javascript?

I've been delving into the world of JavaScript for a few days now, but I've hit a roadblock when it comes to implementing a while loop/switch statement in this animation project.

The idea behind the program is that the image will "level up" and change color after moving 3 times, resetting back to the beginning. I have successfully implemented a gold level up, but I'm looking to add more colors for subsequent level ups. I've been attempting to assign different classes to the animated image based on the counter, but nothing seems to be working. Here's what my code looks like:

$("#go").click(function() {
  var dest = parseInt($("#block").css("margin-left").replace("px", "")) + 100;
  
  if (dest < 400) {
    $("#block").animate({
      marginLeft: dest + "px"
    }, 700);
  } else {
      
    $("#block").animate({
      marginLeft:  "10px"
    }, 100);

    //if counter = 1
    document.getElementById('block').classList.add("gold")
    //if counter = 2
    //document.getElementById('block').classList.remove("gold")
    //document.getElementById('block').classList.add("pink")
       //... etc
    
    //counter += 1 
  }
});

Feel free to click on the link below to see the program in action: http://jsfiddle.net/mept9g1u/

I would greatly appreciate any help or guidance on this matter!

Answer №1

Make sure you initialize your counter variable to 0 prior to the click event listener, this way it won't reset to 0 with each click.

let counter = 0 // ⭐️ Set counter value here

$("#go").click(function() {
  let dest = parseInt($("#block").css("margin-left").replace("px", "")) + 100;

  if (dest < 400) {
    $("#block").animate({ marginLeft: dest + "px" }, 700);
  } else {
    $("#block").animate({ marginLeft:  "10px" }, 100);

    counter++;

    if (counter === 1) {
        document.getElementById('block').classList.add("gold")
    }
    if (counter === 2) {
      document.getElementById('block').classList.remove("gold")
      document.getElementById('block').classList.add("pink")
    }
    // etc.
  }
});

Answer №2

$(document).ready(function(){
    function BoxAnimate(){
    var count= 0;
        while( count < 6){
            $(".boxanimate").eq(count).stop(true, true).delay(1000*count).animate({
                left:"400px"
            });
            count++;
        }
    }

    BoxAnimate();
});
.boxanimate { background:Green; 
        margin-bottom:10px;
        margin-left:30px;
        height:150px; 
        width:150px;
        font-family:Arial;
        font-size:30px;
        text-align:center;
        color:#fff;
        line-height:150px;
        position:relative;
        clear:both;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ani-wrp">
        <div class="boxanimate"> data1 </div>
        <div class="boxanimate"> data2 </div>
        <div class="boxanimate"> data3 </div>
        <div class="boxanimate"> data4 </div>
        <div class="boxanimate"> data5 </div>
        
</div>

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

Adjust the button's hue upon clicking it

The current function is operational. Upon pressing the button, it toggles between displaying "click me" and "click me again". However, I desire the button to appear blue when showing "click me" and red when displaying "click me again". <!DOCTYPE html ...

Employing jQuery to send an ajax request by utilizing an anchor <a> tag

I'm attempting to use ajax to send content to a php script for database storage. My goal is to have a link on the page trigger this action, using jQuery. However, I've been struggling to create a functional function that can handle sending and re ...

The response received from the server was a 404 status () indicating that the resource failed to load

I'm encountering an issue while loading from the web service, and receiving the following error: Failed to load resource: the server responded with a status of 404 () Your help would be greatly appreciated. You can also access the code on JSFiddl ...

React.js: Endless rendering occurs when using setState as a callback function, even after props have been destructured

Issue I am facing a problem with my child component that receives button id-name configurations as props. It renders selectable HTML buttons based on these configurations and then returns the selected button's value (id) to the callback function with ...

Vue's emission system, accessed through this.$emits, unexpectedly ceases functioning mid-function call

Within my Vue frontend, I have a function designed to emit updates to the parent component before and after sending a request to the server. The function in question is as follows: saveUpdates: async function () { const component = { doc: ...

What methods can we use to transform Bootstrap rows and columns to resemble a table design?

Attempt number one did not work due to padding issues in the columns. Attempt number two also failed, leading me to believe I may be making a mistake somewhere. This is what I am aiming for: https://i.sstatic.net/yTz6o.png Can anyone provide some assis ...

Blend a background image using rgba without incorporating a gradient effect

Can you merge a background image with an rgba color without resorting to an rgba gradient? My current CSS3 style appears as follows: html { background: linear-gradient(rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.75)), url("../icons/sombrero.jpg")no-repe ...

Ways to eliminate a particular element from the React state

I need help removing a specific item from my React state. Current scenario: When certain checkboxes are selected, I update their state accordingly. My useEffect hook has the checkboxes state as its dependency, and every time there is a change, I add cont ...

Issue with model not being updated after making a request using $http service

I have a hunch as to why it's not functioning properly, but I'm unsure on how to troubleshoot this. Despite looking at similar questions and answers on SO, I am unable to resolve my issue. My goal is to trigger a service upon page load in order ...

The JSX snippet accurately displays the expected value on some pages, but displays an incorrect value on other pages

{_id === friendId || <IconButton onClick={() => patchFriend() } sx={{ backgroundColor: primaryLight, p: "0.6rem" }} > {isFriend ? ( <PersonRemoveOutlined sx={{ color: primaryDark }} /> ...

selenium tutorial: Testing tooltip functionality with Python

<div class="icon_png information icon_baggageyes" title="getTooltip()"></div> Here, a tooltip is displayed using the getTooltip() function. Is there a method to retrieve the return value of the function for testing with Selenium? ...

What is the best way to secure videos and other static files with authentication in a next.js web application?

My goal is to provide static content, specifically videos, exclusively to authorized visitors. I want to secure routes so that they are only accessible to authenticated users. However, the challenge arises when trying to display a video on a page located i ...

How can I utilize columns from a junction table in the "where" clause in sequelize?

Looking to execute a Sequelize query on multiple related models: SELECT Cou.country_id, cou.country_name, Sta.state_id, Sta.state_name, Dis.district_id, Dis.district_name, Cit.city_id, Cit.city_name, Loc.location_id, Loc.location_name, Sub_Loc.sub_locatio ...

angular corresponding vue binding="$props"

If I wanted to take a shortcut, I could utilize v-bind="$props" to dynamically set key values as shown in the sample below : <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> ...

The issue of NextAuth in connection with Spotify failing to display the user's profile picture

I have recently implemented NextAuth v4 and encountered an issue after authenticating with Spotify. Despite successfully retrieving user information from Spotify, I seem to be missing access to the user's profile picture. Here is the data I receive fr ...

The compatibility of Cross-Origin Requests with Socket.io in a Nginx + NodeJS setup is functioning incompletely

In my server system, I have an nginx and a nodejs server set up. Depending on the subdomain, requests are forwarded to the appropriate NodeJS app using proxy_pass. However, I am facing an issue when trying to use Socket.io from a different origin. The joi ...

Determine the final date using the initial date and length of time

Utilizing a Jquery date picker for selecting a start date and a dropdown menu to choose the number of weeks. The following codes were attempted to extract the end date result but encountered issues: week_number_id.on('change', function(e) { ...

Top solution for efficiently capturing and storing user input in a React JS application: Event Handler

I've recently designed an input field for inputting details of items. In order to effectively capture and save the entered information, which of the following event handlers would be most suitable? onClick onChange onLoad onKeyPress ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

Mongoose encountered a RangeError due to exceeding the maximum call stack size

I need to bulk insert documents into MongoDB using the native driver instead of Mongoose to enhance the writing speed. Mongoose does not support bulk insert of an array of documents, prompting me to bypass it. However, I encountered the "RangeError: Maxim ...