Maintaining the position of an image during animation movements

I am experiencing an issue with a grid of images where, upon clicking one image, all the other images move down. However, the remaining image is pulled to the top left corner. I suspect this is happening because by removing the other images, the remaining image is not recognized as the only one left and is placed in the first position of the grid.

$(document).ready(function() {

  $('#grid li').click(function() {
    $(this).siblings().animate({opacity: 0, top:'15px'},1000);
    $(this).siblings().fadeOut();
  });   

  $('#hidden').click(function() {
    $('#grid li img').animate({width:'339px',height:'211px'});
    $('#grid li').siblings().fadeIn();
    $('#grid li').siblings().animate({opacity: 1, top:'0px'},1000);       
  });
});

HTML

<div class="portfolio">
  <ul id="grid">   
     <li><a href="#"><img src="1.jpg"><span>some text</span></a></li>
     <li><a href="#"><img src="2.jpg"><span>some text</span></a></li>
     <li><a href="#"><img src="3.jpg"><span>some text</span></a></li>
     <li><a href="#"><img src="4.jpg"><span>some text</span></a></li>
     <li><a href="#"><img src="5.jpg"><span>some text</span></a></li>
     <li><a href="#"><img src="6.jpg"><span>some text</span></a></li>
     <li><a href="#"><img src="7.jpg"><span>some text</span></a></li>
     <li><a href="#"><img src="8.jpg"><span>some text</span></a></li>
     <li><a href="#"><img src="9.jpg"><span>some text</span></a></li>
      </ul></div>
 <div id="hidden">

CSS

 ul#grid {
  list-style: none;
  top: 0;
  margin: 60px auto 0;
  width: 1200px; 
}

 #grid li span {
  color: white;
  display:block;
  bottom:250px;
  position:relative;
  width:180px;
}

 #grid li {
  float: left;
  margin: 0 40px 75px 0px;
  display:inline;
  position:relative;
}

JSFIDDLE

Answer №1

A helpful suggestion is to avoid using fadeOut() because it hides the element and causes your image to shift position.

$('#grid li').click(function() {
  // $(this).siblings().css("position","relative");
  $(this).siblings().animate({opacity: 0, top:'15px'},1000, function() {
    // Animation complete.
      $('#grid li img').animate({width:'339px', height:'211px'});
  });
 });  

FIDDLE

Answer №2

There is a method in Prototype called absolutize that may be useful for your situation. If you are using jQuery, you can also consider using this custom plugin:

jQuery.fn.absolutize = function()
{
  return this.each(function(){
    var element = jQuery(this);
    if (element.css('position') == 'absolute'){
        return element;
    }

    var offsets = element.offset();
    var top = offsets.top;
    var left = offsets.left;
    var width = element[0].clientWidth;
    var height = element[0].clientHeight;

    element._originalLeft = left - parseFloat(element.css("left") || 0);
    element._originalTop = top - parseFloat(element.css("top") || 0);
    element._originalWidth = element.css("width");
    element._originalHeight = element.css("height");

    element.css("position", "absolute");
    element.css("top", top + 'px');
    element.css("left", left + 'px');
    element.css("width", width + 'px');
    element.css("height", height + 'px');
    return element;
  });
}

Original Source: Link

You can use this method to lock the size and position of your target element before any changes occur in the DOM:

$('#grid li').absolutize();

Answer №3

One approach would be to utilize Jquery animate in order to smoothly diminish the opacity of the items to zero. The fadeout effect essentially works by decreasing the opacity to zero, then proceeding to hide the object with "display: none" once it reaches that point. In this case, the goal is solely to achieve the fading effect! You could consider employing something along the lines of $('myobjects').animate({opacity: 0}, slow); I hope my syntax aligns correctly here. Thank you!

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

Issue detected in highstock chart. The tooltip is displaying undefined data

I'm working on creating a highstock chart that displays timestamps on the x-axis and numbers on the y-axis. Additionally, I have some extra data in the array that I want to show in the tooltip. Here's a glimpse of the data array: data=[ { "ID": ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...

Apply the "selected" class to the menu located in the common header

I have implemented a menu in the header.php file that will be displayed on all pages such as index.php or contact-us.php. However, I am facing an issue with adding the selected class to the active main category in the menu. The code provided works fine wh ...

Changing the color of a Highcharts series bar according to its value

Playing around with Highcharts in this plunker has led me to wonder if it's possible to dynamically set the color of a bar based on its value. In my current setup, I have 5 bars that change values between 0 and 100 at intervals. I'd like the colo ...

The removal of the Lodash library from node modules is not occurring

In an effort to reduce bundle size, I made the decision to replace all lodash methods with core js methods in my Vuejs project. Despite attempting various npm uninstall commands such as: npm uninstall lodash npm uninstall lodash --save npm uninstall lodas ...

Discovering mistakes in PHP MySQL

Is there an error in this code? Here's the code I'm working with. Thank you in advance for your help! else if(isset($_POST['UPDATECSSGOLD'])) { $stmt = $mysqli->prepare("UPDATE css set STYLE_STATUS = 'allnull'"); $stmt-& ...

Issue with Dotless MVC bundling occurring when attempting to import a specific less file multiple times

Trying to achieve a specific structure using dotless: styles/variables.less - contains all variables like this @color:green; styles/component1.less - random component specific style importing variables.less @import "variables"; body { ba ...

When a parameter is passed into a React-Query function with an undefined value, it can lead to the API returning a 404 error

Two parameters are sent from the frontend to trigger a GET request in another TypeScript file. It seems that one of the parameters is not successfully passed due to unknown rerenders, resulting in a 404 Error being returned by the API call in the console. ...

Elevate the expanded card above the others on hover instead of displacing them downward

I'm working on a grid of cards where hovering over one card expands the bottom section to reveal more content. The issue is, when it expands, it pushes all other cards down. What I actually want is for it to overlay on top of the card below it. Here ...

Modifying a gridview cell through a Modal popup that is displayed using the rel attribute

I have successfully implemented a modal dialog using CSS and the rel="#showEditModal" attribute of a button. This enabled me to add values to the database and update the gridview effectively. However, I am now facing a challenge where I need to be able to ...

Communication between Python and the front-end

I am currently working on a web application that utilizes jQuery for ajax requests to communicate with PHP, which in turn interacts with a MySQL database. I now have the need to implement some machine learning functionalities using Python, specifically for ...

Issue with submitting a form using jQuery's AJAX function

This is the HTML code for my form: <form id="contactForm1" method="POST" action="downloadfile"> <input id="tesst" name="tesst" type="hidden" value="<?php echo $val['file_name'];?>"/> <div id="download" class="btn btn-d ...

Creating an HTML report in Oracle SQL*Plus with alternating row colors

When using Oracle sqlplus, I can easily convert query output into an HTML report by setting "markup html on". This is a simple way to publish a database report online. However, I do miss one thing - alternating colors for every other row. This feature is ...

Steps for transforming Object A into an array of objects, each containing the properties and assigned values and labels from Object A

I have an object with specific key-value pairs and I would like to transform it into an array where each item has a label and a value: { "id": 12432, "application": "pashmodin", "unit": null, "status": ...

When I switch to mobile view, my navigation menu vanishes

Currently in the process of creating a website using WordPress, specifically with a divi theme and utilizing a windows operating system. It seems that everything appears correctly on desktop, however when resizing the window or viewing the site on a mobile ...

What is the best method for converting a string picture URL into an image and showcasing it in an image tag?

I have a URL for an image that looks like this: C:\inetpub\MaujApp\OMSAPI\ManualReceivingImages\WhatsApp Image 2021-03-24 at 12.07.41 PM.jpeg My goal is to convert the original image and display it to the user using jQuery. I woul ...

What could be causing the sluggish performance of this particular MongoDB query?

I'm currently grappling with how to manage a particular situation that will eventually involve date ranges. db.article_raw.count({ "date": {$gt:ISODate("2015-07-08T00:00:00.000Z")}, "searchTerms.term":"iPhone" }) Despite knowing that my indexe ...

Timezones not synchronizing properly with Moment.js

Hello everyone, I am currently exploring the world of moment.js along with the timezone add-on. I'm encountering some issues with a world clock project that involves using moment.js and moment-timezone.js together on a page where highcharts are also p ...

Attempting to modify code to produce HTML output using Selenium in Python

I am currently using Selenium to scrape information from Facebook groups: with open("groups.txt") as file: lines = file.readlines() total = len(lines) count = 1 for line in lines: group_id = line.strip().split(".com/")[1] ...