Smart method for repositioning multiple elements on the display

Imagine we have multiple divs displayed on a screen:

https://i.stack.imgur.com/jCtOj.png

...and our goal is to move them collectively, either to the left:

https://i.stack.imgur.com/KBfXC.png

...or to the right:

https://i.stack.imgur.com/c1cUw.png

An initial approach might involve iterating through each element, capturing its current position, and applying a standard shift amount to all divs, as shown below:

function set_element_positions(new_top, new_left) {
    var all_elems = document.getElementsByClassName("my_div");
    for(var i=0; i < all_elems.length; i++) {
        var rect = all_elems[i].getBoundingClientRect();
        var current_top = rect.top;
        var current_left = rect.left;
        all_elems[i].style.top = current_top + new_top + "px";
        all_elems[i].style.left = current_left + new_left + "px";
    }
}

This function can be triggered during an as_change mouse event. For instance, a slider could invoke this function continuously while being adjusted, resulting in frequent calls to the function.

Initially, this method works effectively with a smaller number of divs, ensuring they move together in real-time. However, performance starts to degrade when dealing with a larger quantity of divs (approximately ~30).

Is there a more efficient strategy to simultaneously adjust the positions of all elements, allowing for rapid modification by a slider in real-time?

Answer №1

Since I'm uncertain about your goal, I will present multiple solutions to the issue based on different scenarios.

Scenario 1: Moving all elements within a single container

If this aligns with your situation, you're lucky as it is the simplest to address. Alvaro's suggestion was correct. In this case, you need a nested container. Allow me to illustrate with a brief example. First, the HTML:

<div id="viewPort">
    <div id="innerContainer">
        <div class="my_div"></div>
        <div class="my_div"></div>
        <div class="my_div"></div>
    </div>
</div>

Then, implement the CSS:

#viewPort {
    /* Customize width/height as needed. */
    width: 300px;
    height: 200px;
    overflow: hidden;
}

#innerContainer {
    position: relative;
    width: 200%;
    height: 200%;
    top: -50%;
    left: -50%;
}

The concept involves an inner container that occupies more space than the outer container, with overflow set to hidden. Upon setup, you can either adjust the top and left properties of the inner container or adjust the scroll positions of viewPort (scrollTop and

scrollLeft</code) for the appearance of movement without actual displacement.</p>
<h1>Scenario 2: Shifting specific elements in a single container</h1>
<p>This scenario presents challenges since the moving container technique is no longer applicable. The scrolling method mentioned above could still function if you designate non-moving elements as <code>position: fixed
. Nonetheless, managing their top and left attributes becomes crucial to maintain their positions.

Despite having similar class names, dynamically updating CSS styling through classes via Javascript isn't feasible due to restrictions on modifying stylesheets. Consider extracting the current transform property values from elements, adding to them, then reapplying using transformX() and transformY() instead of altering left and top directly (Related topic query).

Scenario 3: Development of a game

Javascript operates as an interpretive language which executes at a slower pace compared to compiled languages. Traditional HTML with Javascript wasn't primarily designed for handling intricate gameplay scenarios, with a few exceptions where circumvention of limitations was possible. For creating substantial content with HTML5, consider exploring the <canvas> or <svg> tags and integrating one into your project.

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 dynamic hover drop-down navigation bar in ASP.NET

After successfully creating a navigation bar with hover effects, I am now looking to implement a dropdown list when hovering over the items. Can anyone provide guidance on how to achieve this? Below is the current code snippet I am working with: <ul c ...

I am encountering issues with my XPath in certain scenarios

When attempting to do an assertion with the total of a dynamic table, I am encountering difficulties writing XPath that works for all scenarios. The issue arises because the table sometimes contains only 1 image and other times it may contain 5 images. In ...

importance of transferring information in URL encoded form

Recently, I started learning about node.js and API development. During a presentation, I was asked a question that caught me off guard. I had created a REST API (similar to a contact catalog) where data was being sent through Postman using URL encoded PO ...

How to include images in a PDF using jspdf without encountering issues with Adobe Reader?

For a project I'm working on, I've integrated jspdf to convert some charts into a PDF. The framework I'm using is angularjs 1.5.6, and the charts are created with chart.js. The HTML snippet for the charts looks like this: <div name="char ...

Tips for displaying only a list of folders in elfinder, a jquery file management plugin

Currently, I am working on enhancing the features of a file manager plugin that allows users to manage their folders effectively. One key functionality of the plugin is the ability for users to share specific folders with others. However, if a folder has n ...

Tracking global click events in Vue.js can provide valuable insights into user interactions on your

While working with JavaScript, I was able to create this code for a popover. By clicking on the navbar-link element, the popover will appear or disappear. However, it would be great if I could close the popover by clicking anywhere on the screen (when the ...

Arranging a list based on the child property in a React component

Within my application, I have an array mapped to a map that generates a div with a data-date attribute as shown below: It's worth noting that the array cannot be sorted here since there are no dates available for comparison, only the element ID cons ...

Is there a way to turn off predictive text for reCAPTCHA on my mobile device?

Using reCAPTCHA on a sign-up form can get frustrating on mobile devices, with constant dictionary word suggestions while typing. I am aware of how to disable this feature for normal input fields by adding attributes through JavaScript, but shouldn't ...

Error encountered when accessing Spotify API. The requested action requires proper permissions which are currently missing. Issue arises when attempting to

I am attempting to use the spotify-web-api-node library to play a track on my application const playSong = async () => { // Verify access token with console.log(spotifyApi.getAccessToken()) setCurrentTrackId(track.track.id); setIsPlay ...

Troubleshooting Issues with Loading Styles and JavaScript for Wordpress Plugin in Admin Area

Can someone please help me with troubleshooting my stylesheet and scripts that are not working properly? I have included styles in the stylesheet and an alert in my script file, but for some reason they are not functioning as expected. (I have confirmed ...

Passing Down Instance Methods Using Static References in JavaScript/TypeScript

✋ Exploring the concept of access modifiers from TypeScript, how can we make it relevant for JavaScript developers as well? Let's consider a scenario where a parent class defines necessary members and a shared method: // ParentClass.js export defaul ...

Shuffle math calculations involving subtraction by a percentage using node.js or JavaScript

Hello there! If you want to subtract, say 35%, from a number, you can use methods like this: var valueInString = "2383"; var num = parseFloat(valueInString); var val = num - (num * .35); console.log(val); But have you ever wondered how you could randomiz ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

Bringing in Chai with Typescript

Currently attempting to incorporate chai into my typescript project. The javascript example for Chai is as follows: var should = require('chai').should(); I have downloaded the type definition using the command: tsd install chai After refere ...

Angular 6 throws an error stating: "The property 'push' cannot be read of null."

The Cart model is defined as follows: //declaring a cart model for products to add export class Cart{ id:string; name:string; quantity:number; picture:string; } Below is the code for my app.service.ts: import { Injectable, Inject } fro ...

Adding an input field and icon at the center using ::after

Having trouble centering an input field with an icon after it in a div. I can center the input text easily using text-align:center, but struggling to center the icon added using ::before. The search text is centered, but not the icon How can I center bot ...

Eliminate a targeted class from an HTML string in PHP

I am dealing with a string that looks like this: $string = '<img class="img-responsive animate scale animated" src="image/catalog/blocks/about-banner.jpg" alt="">'; My goal is to delete the img-responsive class from it. Any suggestions o ...

Developing a new class within a function

In this section of the HTML file, I have set up a form to collect email and password information from new users in order to create a new profile: <form name="userInfo"> <fieldset> <legend>Create a new account</legend> ...

JavaScript inheritance through prototypes and the properties of objects

I am currently exploring the concept of prototyped inheritance in JavaScript for a function. This process is well documented in Wikipedia's javascript article. It functions smoothly when dealing with simple JavaScript types: function Person() { t ...

When the child component's form is marked as dirty, the parent component can access it

I have implemented a feature in my application that notifies users about pending changes on a form before they navigate away. Everything works as expected, but I have a child component with its own form that needs to be accessed by the guard to check if i ...