In this jsfiddle the text displays, fades away and is replaced by other text. The fading away works fine but the new text is supposed to fade in and that isn't working. I found a lot of questions like this and all of the solutions said to hide the container the text is in. Some said to use hide() and others said to use display:none. I tried both but neither make a difference. Here's my code. Any ideas on how to make the text fade out?
<div id="mb-holder" class="mb">
<div class="mb-align">
<span id="mb-test"></span>
</div>
</div>
<script>
var msg1 = 'Message 1';
var msg2 = 'Message 2';
$("#mb-test").html(msg1);
setInterval(swapmessages, 2000);
function swapmessages() {
setTimeout(function(){
$("#mb-test").fadeOut(2000, function() {
$(this).hide();
$(this).load(function() { $(this).fadeIn(2000); });
var curmsg = $(this).html();
if (curmsg == msg1) {
$(this).html(msg2);
} else {
$(this).html(msg1);
}
$(this).css("display","inline");
});
});
}
</script>
You have two issues. Firstly your use of the load
event handler on the div
element will never be fired. Secondly you're setting the display
of the element which is immediately over-riding the fade animation.
You can also tidy up the logic slightly by providing text()
with a function to toggle the message being displayed and chaining the delay with setTimeout()
so that the delay and fade are intrinsically linked. Try this:
var msg1 = 'Message 1';
var msg2 = 'Message 2';
$("#mb-test").html(msg1);
swapmessages();
function swapmessages() {
$("#mb-test").fadeOut(2000, function() {
$(this).text(function(i, t) {
return t.trim() == msg1 ? msg2 : msg1;
}).fadeIn(2000);
setTimeout(swapmessages, 2000);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mb-holder" class="mb">
<div class="mb-align">
<span id="mb-test"></span>
</div>
</div>