Tips on navigating back and forth between two arrays

I am currently working on creating a cycling sliding animation for a set of elements using two arrays:

var elms = [elm1, elm2, elm3];
var props = [{x,y,width,height,z-index,opacite,....}, {....}, {....}];

Initially, the elms will be positioned in the same order as the props:

elms[0] -> props[0];
emls[1] -> props[1];
elms[2] -> props[2];

However, I want to cycle them in a specific pattern:

elms[0] -> props[2]
elms[1] -> props[0]
elms[2] -> props[1]

and then:

elms[0] -> props[1]
elms[1] -> props[2]
elms[2] -> props[0]

and so forth...

I attempted to achieve this with the following code:

function index(n, array){
    var m = n;
    if(n > array.length){
        m = n - array.lenth;
    }else if(n < 0){
        m = array.length + n;
    }
    return m;
}

var active = 0; //the front element

function slide(direction){
    for (i=0; i< elms.length; i++)
    {
        elms[i] -> props[index(i - active, props)]
    }
    if(direction == 'fw'){
        if(active++ => elms.length){
            active = 0;
        }else{
            active++;
        }
    }else if(direction == 'bw'){
        if(active-- < 0){
            active += elms.length;
        }else{
            active--;
        }
    }
}

setInterval(function(){slide('fw')}, 3000);

The above code functions correctly, but I believe there might be a simpler and more efficient way to accomplish this cyclic movement. Has anyone come across a better solution that allows looping both forward and backward?

Answer №1

In order to adjust the props array without any issues, you have the option to use the .shift() method to remove the initial element, then add it back with .push() at the end of the array, and finally perform the following:

elms[0] -> props[0];
emls[1] -> props[1];
elms[2] -> props[2];

If you want to rotate the props array, a simple solution is:

function rotateProps() {
    var front = props.shift();
    props.push(front);
}

To execute this action each time, simply call rotateProps() during each cycle and repeat the original steps.

Answer №2

One approach could be to utilize modules. By maintaining a global variable that increments with each shift, you can then apply the modulus operation with the length of the arrays to access elements like this: props[shift%len]

In a scenario where len is 3 (as stated), the following outcomes may be obtained when accessing props relative to the first element index (0):

Check out this proof of concept: jsfiddle.net/Q8dBb. This method enables array access without altering the arrays, potentially resulting in faster processing.

For instance:
shift = 0; // (shift+elmsIdx)%len == 0;
shift = 1; // (shift+elmsIdx)%len == 1;
shift = 2; // (shift+elmsIdx)%len == 2;
shift = 3; // (shift+elmsIdx)%len == 0;
shift = 4; // (shift+elmsIdx)%len == 1;
and so on

Alternatively, employing an object could enhance flexibility for shifting in multiple ways, resetting, or any additional features. Below is an illustration for this:

function Shift(len) {
    var _len = len;
    var _s = 0;
    this.left = function() {
        _s = (_s + 1)% _len;
    }
    this.right = function() {
        _s = (_s - 1);
        if (_s < 0) {
            _s = _s + _len;
        }
    }
    this.get = function(idx) {
        return (_s + idx)% _len;
    }
    this.reset = function() {
        _s = 0;
    }
}

Example usage: http://jsfiddle.net/6tSup/1/

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

ng-view does not support ng-repeat rendering

I have a basic app using ng-view and ng-repeat. Initially, it worked fine without ng-view, but after switching to ng-view, the ng-repeat stopped functioning correctly. Oddly, when I clicked on the "menu" link, it displayed another set of $var instead of ch ...

Enhance your JQuery UI autocomplete feature by including images and multiple fields for a more interactive user experience

I am looking to incorporate Autocomplete functionality that will showcase names and avatars similar to the Facebook autocomplete feature. In a recent post Jquery UI autocomplete - images IN the results overlay, not outside like the demo and in the provide ...

Can Hapi-Joi validate a payload consisting of either an Array of objects or a plain Javascript object?

How can I create a schema to validate payloads for a post call that accepts either a single JS object or an array of objects to be saved in the database? JS object { label: 'label', key: 'key', help_text: 'text' } ...

Refresh the table following the removal of an item

I am currently working on displaying server data in a table. The delete function is functioning properly, but the deleted item only disappears from the table after refreshing the page. Is there a way to trigger a re-render of the component after deleting a ...

AngularJS - returning dynamic functions

index.html <div ng-repeat="object in objects" ng-style="getStyle(object.id)"></div> controller.js [...] $scope.startWidth = 100; $scope.getObject = [...] $scope.getStyle = function(id) { var widthVal = $scope.startWidth; $scope.star ...

Hide the previous dropdown content in Vue JS by manipulating the visibility of the elements

I'm currently working on creating a Dropdown feature, but I'm facing an issue with hiding the dropdown content when another dropdown is clicked. <template> <div class="dropdown-container"> <div v-for="(it ...

What is the best way to showcase two div elements side by side within my carousel

/* Implementing slideshow functionality */ var currentIndex = 0; displaySlides(); function displaySlides() { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); for (i = 0; i ...

What is the largest number within the Java array?

In the process of developing a program where the user inputs their Class ID along with the number of Boxes sold, I am currently faced with the challenge of determining which class out of the ten had the highest box sales. I'm struggling to find a way ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...

Animating a vertical line moving gracefully between two points

I am facing a challenge that requires your expertise. You may have come across an animated line resembling a scanner in various applications. I need something similar, but in the form of a graph. Specifically, I am looking to create a vertical line that a ...

Determining if a number exceeds 3 decimal points using AngularJS

I have encountered a problem where I need to determine if a value has more than three decimal places in AngularJS. Although I am familiar with checking if a value is a whole number or greater than zero, I am unsure how to perform this specific task. Below ...

Issue with Ajax post redirection back to original page

I'm facing an issue with my ajax call where I send multiple checkbox values to a php file for processing and updating the database. The post request and database updates are successful, but the page doesn't return to the calling php file automati ...

Unable to transmit Props to Component - Fluctuating Behavior

I developed a React.js and Next.js application where I needed to pass the User object to all pages. My plan was to then pass this User component to the Head component in order to display different navigation options based on the user's role. Here is w ...

What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below: GetCurrentUserInfo.java package servlet; import java.io.IOException; import java.io.ObjectOutputStream; import java ...

Is it possible to call a JavaScript file located inside a Maven dependency's jar?

In the process of developing a Spring MVC web application using Apache Tiles, I have incorporated JavaScript libraries such as JQuery by including them in the pom.xml file as dependencies. My query pertains to whether I can access these scripts from within ...

Is there a way to retrieve all elements from an array by using the .fetch method?

I'm completely new to the world of Ruby and Ruby on Rails. I have some date data stored in an array, and I'm eager to compare each date with the current date. I managed to use the .fetch method to compare one date with Date.today, and it worked p ...

The onsubmit function is not functioning correctly in combination with Ajax

My current implementation involves utilizing Ajax and Php for user login validation. Unfortunately, the form onsubmit function is not properly functioning. <form action="loggedin.php" onsubmit="return test()" method="post"> Below is the correspondi ...

No results found in Mongoose findOne() callback

I'm currently facing an issue in my node app where I am unable to find a user using mongoose. Below is the code snippet that I am using: var User = require('../app/models/user'); function mongoTest() { var publicAddress = "0x8a6be89793 ...

The video is unavailable due to issues with ImageKit

In my project, I am incorporating ImageKit into the workflow. Currently, I have set up a basic process that only includes the video upload feature. On the backend, I have a lone file named index.js. I haven't developed a frontend yet, so I have been e ...

An error handling event for XHTML compliance, similar to the HTML onerror event, is designed to address the issue of

Below is a piece of code that handles hiding the placeholder (imagecontent) for dynamically populated empty images and their captions: <head> <script type="text/javascript"> function hideEmptyImage() { document.getElementById(&q ...