elethan elethan - 16 days ago 5
CSS Question

Don't reposition remaining elements after jQuery fadeOut()

The following is a simplified example of a slightly less simple game I am working on as practice:

The HTML:

<div>
<img class="small" src="http://vignette4.wikia.nocookie.net/rickandmorty/images/d/dd/Rick.png/revision/latest?cb=20131230003659">
<img class="small" src="https://ih0.redbubble.net/image.111135319.1949/flat,800x800,075,f.u1.jpg">
<img class="small" src="http://67.media.tumblr.com/c38fff03b8dd7aaf75037eb18619da57/tumblr_n436i3Falo1sndv3bo1_1280.png">
</div>


The Javascript:

$(".small").click(function() {
$(this).fadeOut();
});


And here it is in a JSFiddle: https://jsfiddle.net/rzu1yvpa

My Problem:



When I click on one of the images, it fades out as expected, but depending on which image disappears, the remaining images are re-positioned to fill the empty space. How can I make the remaining images keep their positions after other images have faded out? I have been searching and experimenting with this for a while now, but I am new to all things web, and am not sure what I should be looking for.

I have tried changing the
position
and
display
properties, but nothing has worked so far. It looks like
fadeOut()
sets the
display
property of the faded out element to
none
- maybe this is why the remaining images are ignoring them and filling the space? I have also tried putting the images in a bootstrap grid, but haven't been able to get that to work either, and would prefer a non-bootstrap solution.

Answer

jQuery's .fadeOut() and .fadeIn() methods animates the opacity of the matched elements, and once the opacity reaches 0, the display style property is set to none, so the element no longer affects the layout of the page.

This is what is causing the issue, when the display is set to none, the image is removed from the "flow".

You could use jQuery's fadeTo instead, which just fades to a degree of opacity, and does not set the display.

$(".small").click(function() {
    $(this).fadeTo(600,0);
});

FIDDLE