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

Can you provide guidance on transforming a JSON date format like '/Date(1388412591038)/' into a standard date format such as '12-30-2013'?

I have a json that is created on the client side and then sent to the server. However, I am facing an issue with the conversion of the StartDate and EndDate values. Can someone please assist me with this? [ { "GoalTitle": "Achievement Goal", ...

The async and await functions do not necessarily wait for one another

I am working with Typescript and have the following code: import sql = require("mssql"); const config: sql.config = {.... } const connect = async() => { return new Promise((resolve, reject) => { new sql.ConnectionPool(config).connect((e ...

Issue with jQuery ajax in Internet Explorer 6

Hey there, I'm dealing with a strange issue: The success handler in my $.ajax call looks like this: function(data){ alert(data); } Seems pretty straightforward, right? The problem I'm facing is that the data sent by the server is ALW ...

Slide the first div upward to display the text in the second div when hovering over the first div

I'm facing an issue where a div needs to move upwards when hovering over it. To see an example, take a look at this JSfiddle. The desired outcome is as follows: As illustrated, the right div is the one being hovered. I have attempted to create this ...

Is there a way for me to access the current templating in AngularJS?

I am looking to retrieve the HTML page as a string after AngularJS has finished rendering the template. My goal is to send this content to the server. .controller('MyCtrl', ['$scope', '$location', function ( $scope, $location ...

Verify if the JSON attribute is empty

My input contains the following: { "headers": { ... }, "body": { "RequestInfo": { ... , "Identificator": null } } <filter regex="false" source="boolean($ctx:Identificator)"> - check if it exists (even when it's ...

Constructing hierarchical objects in JavaScript

I am looking to create a complex nested object in JavaScript that follows a specific structure. const data = { name: 'Context 1', children: [ { name: 'Option 1', children: [ { name: 'Context&ap ...

How is the server architecture typically designed in a node.js application?

Currently, I am developing a node.js application using socket.io and I'm seeking advice on how to structure the folders properly. The files that I have in my project include: Server.js package.json Additionally, I have: Client.js Index.html Incl ...

PHP function that includes an if statement in its returned value

Having a function that determines a user's role is functioning correctly within the HTML document. However, when multiple functions are involved in connecting to a database and displaying information, I encounter issues with granting access to certain ...

Fixed width blocks automatically adjusting to small containers

When I try to add text to my absolute block inner div, it doesn't expand as expected. I am aware that expanding within a parent container with a specified width, such as <div class="main_wrap"></div>, can be problematic. Unfortunately, I ...

How to Create a React Material UI Switch with Minimal Padding

I need a compact Switch component without any additional dimensions or spacing Check out this custom Switch component <Switch checked={isSubscriptionStatusActive} onChange={onHandleChangeSubscriptionStatus} disabled={subscriptionStat ...

The error message: "Trying to access property 'get' of an undefined object"

$http.get('/contactList'). success(function(data){ console.log('received data from http get'); }). error(function(data) { $scope.error = true; $scope.data = data; return 'error message'; }); There seems to be ...

Streamline a javascript code with numerous elements

Seeking assistance in simplifying this code Currently, I find myself constantly updating this code each time a new entry is uploaded. I am looking for a solution where there is a single script that can identify the element IDs ("#rolly" or "#lagrimas") a ...

Creating dynamic routes for custom locales in Next.js

I'm currently working on a Next.js application with internationalization functionality using next-i18next. Most of my site's pages have been generated in both English and French, except for dynamic routes (like blog/[id]/[blog-title]). For these ...

The app is not showing the Post Request message after it has been sent from the UI front end

I am currently developing a chat application using node.js, express.js, socket.io, and mongodb. However, I have encountered an issue during the Node.js and express.js implementation (socket.io and mongodb are not yet utilized). The problem is that the code ...

Arrangement of cards in a column

As someone who is new to working with CSS, Wordpress, and similar technologies, I am seeking assistance. I am struggling with creating card layouts. My goal is to achieve a layout similar to this, where the cards are displayed in two columns instead of ju ...

What are the distinctions between altering the value of a textarea with JS and user input?

I've come across an interesting scenario that I'm hoping someone with more expertise in JavaScript can help me with. There is a popular online forum site that I frequently use. In the past, I was able to easily update a comment textarea using Jav ...

The specified height for input[type=button] in Firefox/Safari is adjusted by subtracting the padding and border

When implementing the following CSS: input[type=button] { background-color: white; border: 1px solid black; font-size: 15px; height: 20px; padding: 7px; } along with this HTML: <input type="button" value="Foo" /> I anticipate that the t ...

Issues arise when trying to integrate external JavaScript files into a Vue application

I am facing an issue with including external JS files in my HTML document. The website requires these files to function properly. What I have attempted: In the main.js file, I tried adding these imports: import '../../assets/js/jquery-3.5.1.min&apos ...

Using jQuery UI autocomplete feature to dynamically populate search suggestions from an AJAX

I am having trouble retrieving a response within AJAX for jQueryUI autocomplete. The drop down box does not display any results. Here is the script I am using: $(function(){ $("#user_key" ).autocomplete({ source: function(){ var ht ...