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

Automated service worker upgrade procedure

Currently, I have some concerns regarding the update process of the service worker used in my project. Within this project, there are two key files associated with the service worker: The first file, "sw.js", is located in the root of the website and is i ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...

Ensuring continuous user login during webpage refreshes with the help of React and local storage

Currently, I am working on implementing the use of local storage to ensure that upon refresh, the user remains logged in rather than being signed out each time. Successfully, I have been able to store data in local storage by utilizing the following code ( ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

Convert the contents of the uploaded file to a JSON format

I've recently started using angularjs for file uploads and came across this helpful model on github: https://github.com/danialfarid/angular-file-upload The file upload process is working smoothly for me. However, I'm facing a challenge after upl ...

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...

A blank page is appearing mysteriously, free of any errors

I have experience with ReactJs, but I am new to Redux. Currently, I am working on implementing an async action where I call an API and display the data received from it. Initially, when all the Redux components (actions, reducers, containers) were on a sin ...

Exploring the mechanics behind ES6 Map shims

From what I've gathered from the documentation (here and here), it seems that having a reference to the memory address is necessary for the operation to work: const foo = {}; const map = new Map(); map.set(foo,'123'); // This action requi ...

Issue with MUI Grid item not functioning properly when using overflowY: "auto"

I am encountering an issue while using MUI with React. I have a <Paper> element wrapping a <Grid> with 3 children elements. The problem arises when I set the overflowY property of the bottom grid item to "auto" - instead of showing the scroll b ...

A problem arises when the React effect hook fails to trigger while utilizing React Context

I have created a component that is supposed to generate different pages (one for each child) and display only the selected page: import * as React from "react"; export interface SwitchProps { pageId: number; children: React.ReactChild[]; } ...

JQuery form plugin - submitting a form automatically on onchange event

As a beginner in JQuery, I am looking to utilize the JQuery form plugin for file uploads and would like to trigger the form submission as soon as a file is selected. This should occur upon the onchange event of the input tag: myfile. <html> <body ...

Guide on incorporating file uploads in an Angular 6 project

I am currently working on creating a component where I have implemented a file upload function in a child component and am attempting to use that component's selector in another one. Here is my project structure: - upload : upload.component.html up ...

"Error: The function $(...).autocomplete is not recognized" in conjunction with Oracle Apex

Currently experiencing some frustration trying to solve the issue at hand. The Uncaught TypeError: $(...).autocomplete is not a function error keeps popping up and I have exhausted all resources on Stack Overflow in an attempt to fix it. This problem is oc ...

The latest version of Material UI icons caused compatibility issues with React-Select

I recently made the switch from using @material-ui/icons version 4.11.2 to @mui/material and @mui/icons-material version 5.2.3 Although material UI is not directly integrated with react-select, there seems to be some interaction happening. The transition ...

Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons: $('button').on('click', function(){ var btn=$(this); if(btn.attr('class')=='tct-button'){ btn.removeClass('tct-button ...

Is there a way to retrieve the list element that was added after the HTML was generated?

How can I reference a list element added using the append function in jQuery within my onclick function? See my code snippet below: $(function() { let $movies = $('#showList') let $m = $('#show') $.ajax({ method: 'GET ...

What is the best way to adjust the volume vertically?

I successfully transformed my volume slider from horizontal to vertical using CSS. However, the functionality of the volume slider still behaves as if it were horizontal. In other words, I have to click horizontally to adjust the volume instead of vertical ...

Tips for transferring a function from a Node.js server to a client

Hey everyone, I'm trying to achieve the following: On the Node server side: var fn = function(){ alert("hello"); } I am looking for a way to send this function to the client side. I am currently using AngularJS, but I am open to other solution ...

Connecting external websites in XAMPP: A beginner's guide

While using Xampp, I encountered an issue when attempting to access any online website with the following code: <a href="www.xyz.com">Click</a> Instead of directing me to www.xyz.com, it displays this in the URL field: localhost/www.xyz.com ...

Why is Vue JS throwing an error stating "undefined is not an object"?

After creating a Vue app on a single page .html file served by django, which consists of multiple components, I decided to transition this project into a full-fledged Vue.js project using the Vue CLI. Initially, I thought it would be a simple task to trans ...