It is possible to stop an insertBefore, inside an addEventListener, to add a smooth css, so that the movement produced by the insertion of the div is not abrupt for the user?
I have read many questions, i have tried using settimeout in various ways, without success:
JavaScript
x
29
29
1
const gallery = document.getElementById('gallery');
2
3
const frames = gallery.querySelectorAll('.frame');
4
5
for (var i = 0; i < frames.length; ++i) {
6
7
frames[i].addEventListener('click', function() {
8
9
if (this.className == "frame b") {
10
11
//setTimeout( function(){
12
13
gallery.insertBefore(this, this.previousElementSibling);
14
15
//}, 1000 );
16
17
} else {
18
19
//setTimeout( function(){
20
21
gallery.insertBefore(this, this.previousElementSibling);
22
23
//}, 1000 );
24
25
};
26
27
});
28
29
};
JavaScript
1
15
15
1
.frame {
2
width: 200px;
3
height: 100px;
4
font: bold 400% sans-serif;
5
color: white;
6
float: left;
7
}
8
9
.frame.a {
10
background-color: brown;
11
}
12
13
.frame.b {
14
background-color: purple;
15
}
JavaScript
1
4
1
<div id="gallery">
2
<div class="frame a">A</div>
3
<div class="frame b">B</div>
4
</div>
Advertisement
Answer
this
refers to a different context inside your setTimeout
callback; it doesn’t refer to the element for which the event is dispatched anymore.
There are a few ways you could do this, here are 3:
Use an arrow function, where this
doesn’t get bound to a new context:
JavaScript
1
4
1
setTimeout( () => {
2
gallery.insertBefore(this , this.previousElementSibling);
3
}, 1000 );
4
Store a reference to this
for use inside the callback:
JavaScript
1
6
1
const _self = this;
2
3
setTimeout( function(){
4
gallery.insertBefore(_self , _self.previousElementSibling);
5
}, 1000 );
6
Manually bind
the current context to the callback function:
JavaScript
1
4
1
setTimeout( function(){
2
gallery.insertBefore(this, this.previousElementSibling);
3
}.bind(this), 1000 );
4