Maxim Velichkin Maxim Velichkin - 5 months ago 9
Javascript Question

How can I make text to be changed AFTER the div is finally fades in (JS, jQuery)?

I have a javascript function, that writes a text inside a div in html document (using inneHTMLr). This function also have jQuery function, that slowly makes this div unvisible -

$("#descr").fadeOut();
, and then visible -
$("#descr").fadeIn();
before writing text in it.

I can call this function several times, giving it different texts to write. But since the "fade out" and "fade in" effects are slow, i see the text change inside the div, before it fades out and fades in again.

How can I make text to be changed after the div is finally fades in?
I would be grateful for the easiest way.



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var name1 = "name";
var name2 = "3";
var name3 = "Text that I want to write";

function start() {

$("#here").fadeOut();
$("#here").fadeIn();
document.getElementById('here').innerHTML = eval(name1 + name2);
}
function start2() {

$("#here").fadeOut(600);
$("#here").fadeIn(600);
document.getElementById('here').innerHTML = "New text";
}
</script>

<div id="here" style="background-color: green; color: white; display: none;"></div>

<button onclick="start()">
Text-1
</button>

<button onclick="start2()">
Text-2
</button>





P.S. I used two functions here, but in my project I have only one but more complicated function.

Answer

You can give the fadeIn/fadeOut a callback functions as such:

$("#ele").fadeIn(200, function() {
  //code after 200ms
});

Check out jQuery documentation for more info!