Reputation: 53
How I can change 2 texts with fadeIn() and fadeOut() jQuery effects?
Here is an example: Apple website. Below the iPhone image is one box, "Hot News Headlines". See how the news changes? One text fades in, then fades out, and the second is coming.
I'm new to jQuery so please give detailed code. Thanks!
Upvotes: 1
Views: 5949
Reputation: 291
Consider following HTML:
<span class="rotateText">Test</span>
<div class="rotateArray">
<a href="http://www.google.com">Google.com</a>
<a href="http://www.microsoft.com">Microsoft.com</a>
<a href="http://stackoverflow.com">Stackoverflow.com</a>
<a href="http://www.wired.com">Wired.com</a>
</div>
and the script:
$(function () {
// set first
$('.rotateText').html($('.rotateArray a').eq(0));
// enter loop
rotateText();
});
function rotateText() {
var count = $('.rotateArray a').length;
var i = 0;
var loopArr = $('.rotateArray a');
var rotationElm = $('.rotateText');
window.setInterval(function () {
rotationElm
.fadeOut(400)
.queue(function () {
$(this).html('<a href="' + loopArr.eq(i).attr('href') + '">' + loopArr.eq(i).text() + '</a>');
if (++i == count) i = 0;
$(this).dequeue();
})
.fadeIn(400)
;
}, 4000);
}
Upvotes: 1
Reputation: 39848
Let's say that your html is like this:
<div>
<div class='fadey'>1</div>
<div class='fadey'>2</div>
<div class='fadey'>3</div>
</div>
You can do something like:
var faderIndex = 0, //to keep track
faders = $('.fadey'); //cache, so we won't have to walk the dom every time
function nextFade() {
//fade out element over 1000 milliseconds, after which call a function
$(faders[faderIndex]).fadeOut(1000, function() {
//increase the index and do a check, so we won't overflow
faderIndex++;
if (faderIndex >= faders.length)
faderIndex = 0;
//fade in the next element, after which call yourself infinitely
$(faders[faderIndex]).fadeIn(1000, nextFade);
});
}
//get the ball rolling
nextFade();
Live example: http://jsfiddle.net/gpQYW/
Upvotes: 2
Reputation: 298532
You use the callback of the .fadeOut()
function to change the HTML and then fade it in, as there will be flicker in the middle:
$('#foo').fadeOut(500, function() {
$(this).html('<span>Bar</span>');
$(this).fadeIn(500);
});
Upvotes: 0