I am creating a system to upload images with drag and drop, the idea is that each image is added to appear in a grid, I use promises so that the image only appears when it is already loaded with the onload event, but I can not get it to appear with a smooth transition. Here is a simple example of the problem.
let cont = document.getElementById('container')
let btn = document.getElementById('addEl')
btn.addEventListener('click',function(){
let newEl = document.createElement('div')
newEl.classList.add('elemento')
cont.appendChild(newEl)
newEl.classList.add('visible')
})
#container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
width: 100%;
height: 300px;
background-color: tomato;
}
.elemento {
width: 50px;
height: 50px;
background-color: #1a1a1a;
opacity: 0;
transition: opacity 2s ease.in;
}
.visible {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
<button type="button" id="addEl">Agregar Elemento</button>
As far as possible I prefer not to use libraries.
The CSS code is fine (except for your typo
ease.in
in place ofease-in
). The reason it doesn't display yet by adding a delay to the transition (opacity 2s ease-in 2s
) is due to how an element is rendered in the document.When you add the element to the DOM programmatically, at that moment information from a state prior to this event is maintained, that is why when you apply the class
visible
the transition is not made. To make the transition occur, you must force a repaint on the document so that it updates its state.Example
You can also do this by adding the class after a few milliseconds:
I don't recommend using the latter because the amount of time for the DOM to repaint is affected by several factors, which doesn't let you know exactly when it will happen.
The properties that force a repaint are the following:
offset
:offsetTop
,offsetLeft
,offsetWidth
andoffsetHeight
.scroll
:scrollTop
,scrollLeft
,scrollWidth
andscrollHeight
.client
:clientTop
,clientLeft
,clientWidth
andclientHeight
.