Dissolve elements sequentially

I've set up an array to store the IDs of buttons, which are identified as #red, #green, #blue, and #yellow

In addition, I've created a function that randomly selects a color and saves it in another array.

My goal is to loop through the second array using a for loop and apply a fade in/out effect on the buttons for an orderly transition effect.

For instance:

array = ['red','green','blue'];

The red button fades in and out first, followed by green, and finally blue.

However, instead of seeing a sequential fading effect, I notice that the buttons seem to fade almost simultaneously. Could someone please suggest a solution and explain why this is happening?

var buttonColours = ["red", "blue", "green", "yellow"];
var GamePattern = [];

function nextSequence() {
  var randomNumber = Math.floor((Math.random() * 4));
  var randomChosenColour = buttonColours[randomNumber]
  GamePattern.push(randomChosenColour);
}

function playSequence(sequence) {
  for (var i = 0; i < sequence.length; i++) {
    $("#" + sequence[i]).fadeOut(1000).fadeIn(1000)
  }
}

nextSequence()
nextSequence()
nextSequence()
playSequence(GamePattern)
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
  <div lass="row">
    <div type="button" id="green" class="btn green"></div>
    <div type="button" id="red" class="btn red"></div>
  </div>
  <div class="row">
    <div type="button" id="yellow" class="btn yellow"></div>
    <div type="button" id="blue" class="btn blue"></div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Answer №1

The issue in your code arises from running all fade effects simultaneously.

To simplify the process, consider randomizing the input array order and then applying fades to elements sequentially with incremental delays. Here's one possible solution:

// Shuffle logic credit: https://stackoverflow.com/a/2450976/519413 @coolaj86
function shuffle(array) {
  let currentIndex = array.length,  randomIndex;
  while (currentIndex != 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
  }
  return array;
}

var buttonColours = ["red", "blue", "green", "yellow"];
shuffle(buttonColours).forEach((id, i) => {
  $('#' + id).delay(i * 2000).fadeOut(1000).fadeIn(1000);
});
.container .row {
  display: inline-block;
}
.container .row .btn {
  width: 100px;
  height: 100px;
  display: inline-block;
}

.btn.green { background-color: #0C0; }
.btn.red { background-color: #C00; }
.btn.yellow { background-color: #CC0; }
.btn.blue { background-color: #00C; }
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
  <div class="row">
    <div type="button" id="green" class="btn green"></div>
    <div type="button" id="red" class="btn red"></div>
  </div>
  <div class="row">
    <div type="button" id="yellow" class="btn yellow"></div>
    <div type="button" id="blue" class="btn blue"></div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Answer №2

When it comes to Javascript, its default behavior is asynchronous, which means it won't pause for the fade in/out effects unless specifically instructed to do so.

A simple suggestion would be to utilize a setTimeout function, where you can find more details and alternatives here

For instance, if you modify this section:

for (var i=0 ; i<sequence.length ; i++){
    $("#" + sequence[i]).fadeOut(1000).fadeIn(1000)
}

To this new version:

for (var i=0 ; i<sequence.length ; i++){
    setTimeout(function() {
         $("#" + sequence[i]).fadeOut(1000).fadeIn(1000)
    }, 2000)
}

The script will now wait for 2000 milliseconds before progressing to the next iteration in the loop.

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

Comparing the impact of mixins styles versus additional style rules

I have customized mixins for a red button. For example: .btnRed{ background:red; color:white; border-radius:3px; min-width:200px; font-size:18px; } I typically use this to style my main buttons, but for one specific button, I n ...

Error message: Missing dependency in React useCallback linting documentary

Within my component, I have integrated a custom hook called useInstantSearch. However, when I try to wrap it in useCallback, an error occurs: I receive the message - React Hook useCallback received a function whose dependencies are unknown. Pass an inline ...

Tips for running a JavaScript statement multiple times in the browser console

When I enter the following JavaScript statement in the browser console: inbreedingInvite('74011','107433',''); and press enter, it sends an invitation to user number 107433 to join group id 74011. If I want to invite another ...

Switching the image by clicking on the link

Looking for assistance with a code that displays three button images and fades in the relevant div when clicked using jQuery... http://jsfiddle.net/ttj9J/11/ HTML <a class="link" href="#" data-rel="content1"><img src="http://i.imgur.com/u1SbuRE ...

Exploring the concepts of angularjs $apply and $scope within the context of object manipulation

In nearly every software application, there is a necessity to modify objects. In my scenario, I have a list of objects that can be edited on the fly with the help of Angular. However, this leads to a dilemma as exemplified by the following controller: ...

issue with allocating memory in Node.js due to node::smalloc::Alloc

I am a beginner with node Js and I have created a basic server that sends me back a zip file upon request. Everything was working fine, but after a few requests, a crash occurred and I saw this message in the terminal: FATAL ERROR: node::smalloc::Alloc(v8 ...

Obtaining the calculated background style on Firefox

Back when my userscript was only functional on Chrome, I had a setup where I could copy the entire background (which could be anything from an image to a color) from one element to another. This is how it looked: $(target).css('background', $(so ...

Ajax/jquery trigger in Contact Form 7 is not working as it should be, it is not

Fellow programmers, I recently acquired a client who prefers using Contact Form 7 as a form plugin. I have no complaints about his choice, especially since I managed to get the Ajax functionality working smoothly. However, something is bothering me. Deve ...

Parsing JSON data to extract values stored in a two-dimensional array

In order to develop a basic version of Tic Tac Toe, I decided to store game data in a JSON file. Here is an example of how the file is structured: [ { "turn": "x", "board": [ [ " ...

How to dynamically assign a value to ng-click directive in AngularJS

Is there a way to dynamically set a value into ns-click? For example: <td ng-click="{{schedule.action}}" ng-init="schedule.action=schedule.action" ng-repeat="schedule in room.Schedule">{{schedule.firstName}}</td> I encountered the following e ...

The error message regarding pdf.worker.min is stating that the use of 'import' and 'export' is limited to within module code and cannot be used outside of it

Upon attempting to deploy a build to Vercel, I encountered the following error message: Failed to compile. static/media/pdf.worker.min.50acc843.mjs from Terser x 'import', and 'export' cannot be used outside of module code ,-[18:1 ...

Installing libraries using npm can be done in two ways: using the command `npm install`

While working, we encountered an issue where the icon for the menu block from the rc-menu library was not displaying. Every time we run mvn install We also run npm install In our package.json file, we had included this library "rc-menu":"^5.1 ...

What is the best way to locate an element through its parent?

I am working with the following HTML structure: <div class="row" id="row-1"> <div class="row-wrapper"> <div class="cell-1"></div> <div class="cell-2"></div> <div class="cell-3"></div> ...

"Modify marker icon upon click event in Google Maps by utilizing the loadGeoJson function

I have successfully loaded the markers from a json file using loadGeoJson. While I am able to SET the marker icon/img on load, I am unsure of how to CHANGE it upon click. Is there a way to target the clicked marker and perform a setIcon or similar action ...

having trouble getting jQuery .submit() function to trigger

I am having trouble getting jQuery's .submit() function to work on my form. I have successfully tested an alert when placed within $(document).ready(), but I cannot seem to get it to trigger on form submission. Here is the script I am using in the BO ...

Exploring Angular's capabilities with filtering and handling $http promises

Having an issue with filtering data from a JSON file that contains an array of 20 objects. Within my factory, I have implemented two functions: function fetchData() { return $http .get('mock.json') .success(_handleData) ...

Generate all possible arrangements of zeros and ones in a two-dimensional matrix with dimensions of n by n

Looking to create a function that will generate an array of all possible 2D arrays consisting of 0s and 1s in JavaScript within a square 2D array. Essentially, this is similar to the question posed here: Make every possible combination in 2D array However ...

Concealing figcaption for smaller screens

Currently revamping my outdated website to make it responsive. I tend to piece together code snippets without fully grasping them, so seeking straightforward guidance. The original site used subcontent divs for captions toggle. You can view it here: http:/ ...

Issues with websockets functionality have been reported specifically in Firefox when trying to connect to multiple

I am currently working on a websocket client-server application. The client code is as follows: const HOST = "wss://localhost:8000"; const SUB_PROTOCOL= "sub-protocol"; var websocket = new WebSocket(HOST, SUB_PROTOCOL); websocket.onopen = function(ev ...

How to update a deeply nested object using a single function in a React component

I have a specific object that requires altering the Ethereum value, for instance; const [reportData, setReportData] = useState({ nameOrganization: "test5", socialMedia: "test", country: "aa", discord: "test", ...