Tips for updating the left positioning of a Div element on the fly

Although my title may not fully explain my goal, I am dealing with dynamically created div elements. When a user triggers an ajax request to delete one of the divs, I want to remove it from the DOM upon success. The issue arises in adjusting the layout after removal - specifically, filling the empty space left by the deleted element by shifting the position of its immediate siblings.

  <div class="carousel-inner">
      <div class="mycrousel" id="photo1" style="left:10"></div>
      <div class="mycrousel" id="photo2" style="left:120"></div>
      <div class="mycrousel" id="photo3" style="left:230"></div>
      <div class="mycrousel" id="photo4" style="left:340"></div>
      <div class="mycrousel" id="photo5" style="left:450"></div>
      <div class="mycrousel" id="photo6" style="left:560"></div>
      <div class="mycrousel" id="photo7" style="left:670"></div>
      <div class="mycrousel" id="photo8" style="left:780"></div>
      <div class="mycrousel" id="photo9" style="left:890"></div>
      <div class="mycrousel" id="photo10" style="left:1000"></div>
  </div>

All these divs are aligned horizontally from left to right. For instance, if the user deletes the div with id=photo5, I aim to reduce the "left" property of all subsequent divs (photo6 to photo10) by 110 pixels each to fill up the vacant space.

function scrollThumb() {
            var $scrollWidth = 110;
            var $photoId = 'photo5'; //id of the deleted photo
            var $totalPhoto = $('.carousel-inner > div').length; //get total number of remaining divs
            
            $('#photo6').animate({
                left: "-=" + $scrollWidth + "px"
            });
            $('#photo7').animate({
                left: "-=" + $scrollWidth + "px"
            });
            $('#photo8').animate({
                left: "-=" + $scrollWidth + "px"
            });
            $('#photo9').animate({
                left: "-=" + $scrollWidth + "px"
            });
            $('#photo10').animate({
                left: "-=" + $scrollWidth + "px"
            });

}

The code above serves as a basic outline of my objective. I do not wish to hardcode the adjustments and instead seek a dynamic solution. It's worth noting that using a counter variable won't suffice due to the non-sequential nature of the ids. Any assistance or alternative ideas are greatly appreciated. Thank you in advance.

EDIT: https://i.stack.imgur.com/9AoiR.png

In light of the updated information with the image reference, consider a scenario where there are initially four images displayed. Upon deleting one, I need to automatically adjust the "left" property of the remaining two images on the right side of the deleted one by reducing their left values by 110 pixels each. This adjustment is necessary to maintain the layout when using absolute positioning. Your suggestions and help are welcome. Thanks.

Answer №1

Check out this small jsfiddle I created, hopefully it meets your needs: https://jsfiddle.net/j45x4qjx/

Below is the function :

function deleteDiv(selector) {

  var mycrousel = $('.mycrousel');
  var div = $(selector);
  var divIndex = mycrousel.index(div);
  var otherElem;

  if (divIndex === 0) {
    otherElem = $(mycrousel.get(divIndex + 1));
  } else {
    otherElem = $(mycrousel.get(divIndex - 1));
  }

  // Calculate the left value between two elements
  var leftElem = parseInt(div.css('left'));
  var leftOtherElem = parseInt(otherElem.css('left'));
  var leftPx = Math.abs(leftElem - leftOtherElem);

  // Remove the selected div
  div.remove();

  $('.mycrousel').each( function( index, element ) {
    if (index > divIndex - 1) {
     var $element = $(this);
     var left = parseInt($element.css('left'));
     // Get the new value of left or set to 0 if negative
     var newLeft = Math.max(0, left - leftPx); 

     $element.animate({
         left: newLeft + "px"
     });
    } 
  });

 }

Simply provide the selector of the div you wish to remove, and let the function calculate the pixel distance between that div and the nearest one before subtracting that amount from all other divs.

Answer №2

Is there a specific reason to identify the deleted image? Ultimately, what you're looking for is a well-organized list of images. I believe this solution should meet your needs:

function organizeImages() {
  var $imageWidth = 120;
  var $initialPosition = 20;
  var counter = 0;
  
  $('.gallery-container > img').each(function(){
    $(this).animate({
      left: ($initialPosition + $imageWidth*counter)+"px"
    }, 400);

    counter++;
  });                                       
}

Answer №3

Your method of approach is highly inefficient, resulting in lag and jank when viewing this code on a mobile device.

A more effective solution would be to group all images within a parent element and scroll that container instead. By doing so, you can eliminate the need for multiple selectors and individual animations on each image.

In cases where an image is deleted, utilizing CSS properties can easily fill the void left by the removed image. Additionally, incorporating creative CSS animations can enhance the transition effect seamlessly!

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

Outputting PHP code as plain text with jQuery

My aim is to set up a preview HTML section where I am encountering a difficulty. I am struggling to display PHP code when retrieving and printing it from a textarea in the HTML. Here are my current codes, This is the HTML area where the textarea code will ...

Form using Ajax technology, including two drop-down menus sourced externally

Is there a way to automatically populate a second drop-down list with all models once a selection is made in the first drop-down on a form? Below is the code snippet: <form> <div class="landing_quote_left"> ...

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

What causes the high memory consumption of the 'readdirSync' method when handling directories with a large number of files?

Consider the NodeJS code snippet below: var fs = require('fs'); function toMb (byteVal) { return (byteVal / 1048576).toFixed(2); } console.log('Memory usage before "readdirSync" operation: ', toMb(process.memoryUsage()['heap ...

Enhancing Canvas with a JPEG layer using the Caman library

I'm currently working with the Caman library to manipulate an image. My goal is to overlay a jpeg onto the manipulated image, but I'm facing a challenge. Although I can briefly see the jpeg beneath the manipulated image, it quickly gets overlai ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

How can I display a pattern using Javascript?

Can you help me create a JavaScript program using a for loop to print a pattern with n number of asterisks and numbers like this: 1 2 3\n 4 5 6 \n 7 8 9 ...

Issue with collapsing custom-height navigation bar in Bootstrap 4

I have implemented a Bootstrap 4 navbar with a brand logo image sized at 150px x 33px. Now, I want to increase the height of the navbar to 80px. To do this, I added min-height: 80px; in my CSS. <!DOCTYPE html> <html lang="en"> <head> ...

Exploration of jQuery Dropdown Menus

Encountering a problem with my dropdown menu. Check out the code here: http://jsfiddle.net/xY2p6/1/ It seems like a simple issue that I can't figure out, but as shown in the link, the functionality is not working properly. I need help linking the hid ...

Experiencing difficulty modifying the information within a particular meta tag using JQuery

I am attempting to modify the content of a meta tag using JQuery, but I keep encountering an error: unidentified expression: [name=dc.description] This is the code I'm currently using: $('meta[name=description]').attr('content', ...

Using Node.js and the Azure DevOps Node API, you can easily retrieve attachments from Azure DevOps work items

Encountering a problem while attempting to download an attachment for a work item in Azure DevOps. Utilizing the node.js 'azure-devops-node-api' client (https://www.npmjs.com/package/azure-devops-node-api) to communicate with ADO API. Retrieving ...

Iterating through a SASS map and retrieving the next item in the loop

I am working with a color array that looks like this: $colors: ( 'primary': '#aaa', 'secondary': '#bbb', 'color-3': '#ccc', 'color-4': '#ddd', 'color-5': & ...

Error: Attempting to access the 'client' property of an undefined object

I'm currently working on a basic discord.js bot. Below is the code snippet that generates an embed: const Discord = require('discord.js') require('dotenv/config') const bot = new Discord.Client(); const token = process.env.TOKEN ...

Exploring collapsible data tables in Angular with Bootstrap styling

I am attempting to transform my static bootstrap data table, which displays the total count of fruits harvested in various months in an incremental manner, into a dynamic one using the JSON provided below: JSON { "fruit": [ { "fruitName": "Al ...

Forming a space between borders

I'm attempting to create a space within a div's border that can accommodate an image, much like so: Is there a method to achieve this using only CSS? The only solution I have found is: .box { background: url(img.png) bottom left; border ...

Centering an unordered list and ensuring the image is responsive across different screen sizes are both top priorities for this design

Currently, I am working on an HTML project through freecode academy and encountering some obstacles. My goal is to center align the unordered list and make sure that the image responds well to various screen sizes. Please feel free to leave comments with ...

Creating custom functions within views using Sencha Touch 2

I'm having trouble creating my own function in Sencha Touch 2 and I keep receiving an error: Uncaught ReferenceError: function22 is not defined The issue seems to be coming from my Position.js file located in the View directory. Ext.define(' ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

Creating a button that seamlessly adapts to all browsers

I am encountering an issue with the positioning of a chat button on my website. Despite my efforts, the button does not remain in the desired location across different browsers and screen resolutions. The browser zoom also causes inconsistencies in the but ...

Utilizing Highcharts with NodeJS

Is anyone familiar with implementing Highcharts in Node.js? I am currently encountering a problem using [email protected]: var Highcharts = require('highcharts'), chart = Highcharts.chart(null, { series: [{ data: [1, 3, 2, 4 ...