Alter the stacking order of a randomly selected element every second

Utilizing an Express server, I am retrieving card data with node-fetch and presenting each one in a div through a loop in an EJS template. By applying CSS properties, I position each card on top of one another at the same location. How can I implement a function to randomly select a card every second for 15 seconds to be displayed on the top of the stack?

This is the code snippet for the server:

import express from 'express'
import fetch from 'node-fetch'

async function getAllCards(req, res) {
  const data = await fetch('https://pokeapi-enoki.netlify.app/')
  const response = await data.json()
  res.render('home.ejs', { response })
}

const app = express()
app.get('/', getAllCards)
app.use(express.static('views'))

const listener = app.listen(null, () => {
  console.log(`Example app listening on port ${listener.address().port}`)
})

Below is the EJS template used:

<html>
    <head>
        <link rel="stylesheet" href="styles.css" />
    </head>
    <body>
        <% for(let i=0; i<response.pokemons.length; i++) { %>
            <div class="Card" id="<%= response.pokemons[i].id %>" style="zIndex: 0; background-color: <%= response.pokemons[i].background_color %>">
                <div class="header">
                    <p class="name"><%= response.pokemons[i].name %></p>
                    <p class="level">Niv. <%= response.pokemons[i].level %><%= response.pokemons[i].abilities[0].icon %></p>
                </div>
                <div class="image">
                    <img src="<%= response.pokemons[i].image %>" alt="" srcset="">
                </div>
                <% for(var a=0; a<response.pokemons[i].abilities.length; a++) { %>
                    <div>
                        <div class="abilities">
                            <span class="AbIcon"><%= response.pokemons[i].abilities[a].icon %></span>
                            <span class="AbName"><%= response.pokemons[i].abilities[a].name %></span>
                            <span class="AbLevel"><%= response.pokemons[i].abilities[a].power %></span>
                            <p><%= response.pokemons[i].abilities[a].description %></p>
                        </div>
                    </div>
                <% } %>
            </div>
        <% } %>
    </body>
</html>

Lastly, here's the corresponding CSS styling:

.Card {
  position: absolute;
  border: 2px solid yellow;
  border-radius: 10px;
  font-size: 8px;
  margin-top: 10%;
  margin-bottom: 50px;
  margin: auto ;
  height: 360px ;
  width: 250px;
}

Answer №1

To implement this method, you can utilize the setTimeout() function to initiate a process that will gather all the cards, randomly select one, and adjust its zIndex attribute accordingly. It is important to ensure that the zIndex is reset before moving on to the next card in order to prevent any sticking issues. Below is an example of how this can be achieved within your HTML body:

<script type="application/javascript">
    const cards = document.querySelectorAll('.Card');
    const startTime = new Date();

    function shuffle () {
        const index = Math.floor(Math.random() * cards.length);
        cards[index].style['zIndex'] = 1;
        setTimeout(function() {
            cards[index].style['zIndex'] = 0;
            const timeNow = new Date();
            const elapsed = timeNow - startTime;
            if (elapsed > 15000) return; // Time limit reached.
            shuffle();
        }, 1000);
    }

    setTimeout(shuffle, 1000);
</script>

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

Tips for querying with Group by and finding the MAX(id) in Sequelize.js

Hello! I'm looking for advice on how to group data by a specific ID and find the maximum value associated with that ID. Let's use the Table Student Quiz as an example: id student_id score 1 2 200 2 2 100 3 ...

Python Selenium error: NoSuchElementException - Unable to find the specified element

Coding Journey: With limited coding knowledge, I've attempted to learn through various resources without much success. Now, I'm taking a different approach by working on a project idea directly. The goal is to create a program that interacts wi ...

Adjusting the height of a div according to the changing heights of other divs

The sidebar contains a search field, two lists, and a text div. The height of the search field and text div always remains constant, while the heights of the two lists vary dynamically. I am exploring the possibility of using only CSS to make the height o ...

Transition effects applied to images with transparency using CSS

My collection includes three transparent PNG images: https://i.sstatic.net/80Jxj.png https://i.sstatic.net/Eewcq.png https://i.sstatic.net/VXk7A.png I have arranged them using the following HTML/CSS: <div style="position: relative; left: 0; top: 0; ...

The year slider on d3 showcases the specific regions between each incremental step

I am working on creating a step slider in d3 (v5) that spans from the years 2000 to 2021 using the d3-simple-slider plugin. const slider = sliderBottom() .min(new Date(2000, 1, 1)) .max(new Date(2020, 1, 1)) .tickFormat(d3.timeFormat(& ...

Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface. However, I encount ...

Methods for identifying Flash and guiding the user through installation

When visiting http://www.plupload.com/example_custom.php without flash installed, a popup box is launched: I'm curious about the method they are using to achieve this. Is it through jQuery JavaScript code snippet or another technique? Additionally, ...

Loop through each input element in the form to retrieve the Name and Value using Javascript

I have been honing my JavaScript skills lately, after relying heavily on JQuery in the past. Though I am quite experienced with jQuery, my knowledge of raw JavaScript is limited. I decided to take on the challenge of learning pure JavaScript just like I ...

How can I utilize an external file in Node js to output as a response?

I came across a similar inquiry, but I am interested in exploring manual methods. My goal is to achieve this without relying on express or any other external library. var http = require('http'); var server = http.createServer(function(req, res) ...

Steps to get the vehicle approaching the creature

Recently, I ventured into the realm of game development and created a car game where the vehicle moves automatically. However, when the car collides with a monster, I want it to start moving towards the monster instead. After some research, I decided to in ...

Encountering a socket's unavailability due to pre-bind connection

I've been utilizing zeromq in my node.js server to send messages to my worker. To accomplish this, I create a socket named "router" on the node.js side. var sender = zmq.socket('router'); sender.bind('tcp://127.0.0.1:6633', functi ...

Is there a way to retrieve the coordinate values using a NodeJS MongoDB query?

"_id" : ObjectId("607ce141dfc52641ea652fb2"), "Timestamp" : ISODate("2020-11-18T02:38:22.000+0000"), "Class" : "Class A", "MMSI" : 219022256, "MsgType" : &q ...

Where can content-tag and main-tag be found in vue-virtual-scroller?

I've been trying to wrap my head around the vue virtual scroller. I couldn't help but notice in the demo that it utilizes a few HTML attributes... <virtual-scroller v-if="scopedSlots" class="scroller" :item-height="itemHeight" :items="items" ...

Move the object in Three.js by rotating it around the origin (0,0,0) in response to mouse

I am currently working with an object in Three.js that was created in Blender and imported into the Three.js format. My goal is to enable mouse rotation for this object. Any assistance on how to achieve this would be greatly appreciated! Thank you. ...

Clicking on the LI element will automatically trigger a click event on the input radio button

Whenever I click on an li element, I want the corresponding radio input to be selected. However, when I try to do this, I'm seeing an error in the console log: Uncaught RangeError: Maximum call stack size exceeded How can I resolve this issue? Bel ...

Store temporary information until response is sent - Node.js

As I develop my express server application, I have a multitude of API endpoints that I have configured. For most of the create and update requests, it is necessary for me to store the userId of the requesting user for logging purposes. To achieve this, I h ...

Is it possible to specify the compile library directory for npm in the 'npm install' command?

I am currently troubleshooting a bug in my application that is running on node.js. To isolate the issue, I have decided to use a custom version of node (not the default system install) to run my application. In my start script, I usually change: #!/usr/bi ...

Tips for altering the orientation of documents in Docusaurus

Instead of having a landing page on my Docusaurus 2 site, I redirect to the first .md file in the sidebar following instructions from this link: Now, I'm looking to create a multi-language website with English and Persian. The Persian version needs t ...

Developing a single page application with AngularJS and ExpressJS that involves dynamically injecting templates

I'm currently developing an application using angularJS and nodejs/expressjs. Upon accessing the application's URL, I need to verify if the user is already logged in. If they are, I want to display the homepage of the application. Otherwise, I n ...

Tips for regularly retrieving information from a psql table

I have a scenario where I am retrieving data from a psql table and converting it into a JSON array to be used for displaying a time series chart using JavaScript. The data that is passed needs to be in the form of an array. Since the data in the table get ...