Shuffling images in JavaScript using z-index for a dynamic deck effect

My current code stack images like a deck of cards with changing z-Index values to create an animation. However, I am looking to make the animation reverse as well and not just go forward in a linear manner. I'm seeking ideas on how to achieve this without providing specific code. Any suggestions are appreciated as I work on implementing them myself later :)


var imageArray = [];

function placeImage(x) {
    var div = document.getElementById("div_picture");
    div.innerHTML = ""; // clear images

for (counter=1;counter<=x;counter++) {
    var image=document.createElement("img");
    image.src="bola/bola"+counter+".png";
    image.width="500";
    image.height="500";
    image.alt="bola"+counter;
    image.id="imagem"+counter;
    image.style.backgroundColor="rgb(255,255,255)"
    image.style.position="absolute";
    image.style.zIndex=counter;
    div.appendChild(image);
    imageArray[counter-1] = document.getElementById("imagem"+counter);
    }
};

var imageShuffle = function(x) {
    imageArray[x-1].style.zIndex=0;
    for (counter=0;counter<x;counter++) {
        imageArray[counter].style.zIndex++;
    }
    imageArray.splice(0, 0, imageArray[x-1]);
    imageArray.pop();
};

window.onload = function() {
    placeImage(14);
    document.getElementById("div_picture").onclick=function() {setInterval("imageShuffle(14)",1000/14)};
};

Answer №1

To organize and manipulate images, you can store pointers to the images in an array and utilize the Array.prototype.sort method from MDN. This approach allows you to have an array of images in any order, giving you the flexibility to manipulate them as needed.

 imgs = document.getElementsByTagName('img'); //In case images are not already stored in an array.
 //First, define a function to sort by zIndex

function sortZ(a, b) {
    //Ensure that z-index is defined, if not set to zero
    var b = b.getAttribute('z-index') ? b.getAttribute('z-index') : 0;
    var a = a.getAttribute('z-index') ? a.getAttribute('z-index') : 0;
    if (a < b) {
        return -1;
    }
    if (a > b) {
        return 1;
    }
    return 0;
}

function convertDomObject(domObject) {
    var domArr = [];
    for (var i = 0; i < domObject.length; i++) {
        domArr.push(domObject[i]);
    }
    return domArr;
}
var imgsArr = convertDomObject(imgs); //Now you can use it!
imgsArr.sort(function (a, b) {
    return sortZ(b, a)
})

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

Creating a JavaScript anchor through a backend bean function

Is it crazy to want to create an anchor that can be called from a backing bean method using JavaScript? I need to do this for specific reasons, utilizing a commandButton with ajax set to false. I'm attempting the following approach: RequestContext.g ...

Checking for the Existence of a Class Element within a String using JavaScript

Within my web project, there is a scenario where if a user has been logged out in one browser tab, they will automatically be redirected to the login page in any other browser tab after interacting with that page (such as clicking on a link). However, this ...

Is it possible to trigger the @click event in Vuejs when utilizing v-html to render HTML content?

Here is an interesting HTML scenario: errorText: '<a class="button" @click.prevent="enableExceedable(issue.mapping)">Enable exceedable limits</a>'; I am trying to insert this string into the following div: <div v-if="hasIssue != ...

Converting text to JSON using JSONP with jQuery's AJAX functionality

Potential Duplicate Question 1 Possible Duplicate Inquiry 2 I have been searching for a definitive explanation on JSONP across various questions but haven't been able to find one yet. For instance, I am attempting to make a cross domain request us ...

Tips for inserting information from a JSON file into a mailto hyperlink

As a newcomer to JavaScript, I am eager to tackle the challenge presented below: Situation: In possession of a JSON file containing personal details such as name, email address, bio, etc., my task is to design a basic web page showcasing this data for ea ...

Tips for utilizing Async/Await within an expressjs router

Having trouble with Async/Await in my Nodejs project. I'm a beginner with Nodejs and facing an issue connecting to my mongodb collection through my repository. When I integrate my controller with the repository, I end up getting a null response. Take ...

Leverage jQuery to automatically submit an ajax form once all ajax requests have been successfully executed

I have integrated a WordPress plugin for store locator on my website. For pages without the interactive map, I have set up a form that serves as a location search tool. To clarify, the form includes a location field where users can input their desired loc ...

In React, I'm unable to navigate to a different page

My English may not be the best, but I am working on creating a Login Page. The issue I'm facing is that when I click the Login button, I want to navigate to the Home Page I designed using React. However, whenever I try to implement Link or Route comma ...

Configuring settings for gulp-jshint

I'm currently utilizing gulp to compile my JavaScript code. My intention is to run jshint on the files before concatenating them, but I'm encountering difficulties in configuring the options properly. Am I handling this process correctly? var re ...

Error occurred while attempting to execute the method

Here's a MongoDB Mongoose query we're dealing with: sampleSchema.find({ $where: "expired <= " + (new Date()) }) .limit(9) // Problems may arise from here .sort({ postedDate: -1 }) .then((docs) => { console.log(&apos ...

React is unable to access and retrieve data from a web API

Currently, I have a controller set up in web-api for my project. I am using React v18.2.0 and NextJS v13.3.0 to work with this setup: public List<ReturnDat> Get() { List<ReturnDat> lst = new List<ReturnDat>(); lst.Add(new ReturnD ...

Using an object as a parameter in a NodeJS function

This past week, I encountered a challenge that has been difficult to overcome. I've been attempting to pass a JSON object as a parameter in a function, but I keep receiving an error message stating that it's not possible. Unfortunately, I don&apo ...

What methods can I use to achieve a stylish and responsive design for my images?

I have been encountering difficulties styling the images for my website. Despite multiple attempts, I am unable to apply CSS properties such as border-radius and responsive design to the images on my page. The images load fine, but they do not seem to acce ...

Execute Cheerio selector once the page has finished loading

Hey there! I'm trying to extract the URL value of an iframe on this website: I've checked the view page source but couldn't find the iframe. Looks like it's loaded after the page is fully loaded through JavaScript. Could it be that ...

Is it possible to find out which JavaScript file the AJAX function is using to send a request to a Java servlet?

I am facing an issue with two js files, one.js and two.js. Both of these files make ajax requests to the same Java servlet class(AppController.java). Here is the code from one.js: function addOne(){ var formData = $('#form1').serialize(); ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

The mouse movement event will not be triggered for every frame when a keyboard event occurs

When the mouse is moving in a browser, ideally the mousemove event should fire every frame. However, if a key is pressed or released (or repeated), the mousemove event stops firing for a frame or two. To test this behavior, you can use the code snippet bel ...

Harness the power of AngularJS by crafting your unique

Hey there! I'm having a bit of trouble figuring out why this isn't showing up. Both View1.html and View2.html are in the partials folder, so that's not the issue. Sometimes the screen is completely blank, other times I only see a Name: label ...

Regular expression that can be used to extract information from a text file by filtering and returning only

When I open a text file, it contains several lines like the examples below. surname australia enter name j.jonhs enter name j.cause enter name f.london enter I am seeking assistance to modify the code snippet below so that it captures the first line m ...

Can we expect Karma to receive updates for upcoming versions of Angular and Jasmine?

We recently attempted to upgrade our company's Angular module, which required updating dependencies as well. Upon upgrading to the latest versions, we encountered an issue with the Jasmine-karma-HTML-Reporter due to its reliance on Jasmine-core 4.x.x ...