Reputation: 181
I am trying to fade in the elements wrapped in span tags randomly. There are a few examples on stackoverflow, but I cannot get them them to work in my code.
Also.. Is there a more elegant way of doing this than wrapping every single word in span tags?
I am trying to turn akll the spans into an array, then select an element in that array at random, and fade it in via changing the opacity of that element, then remove it from the array Here is a jsfiddle of myy attempt..
https://jsfiddle.net/jnghna9s/2/
My script.js:
$(document).ready(function() {
$("#contact").click(function() {
var spans = $("#changingP span").get();
for(var i =0; i < spans.length; i++) {
var index = Math.floor(Math.random() * spans.length);
$(spans[index]).fadeTo(200, 1, function() {
spans.splice(index,i);
}
})
});
});
Upvotes: 1
Views: 183
Reputation: 10996
@dfsq answer is good. For geeks like me interested in the jQuery-less version, the following will do too: (see fiddle)
function randomFade(elements) {
var shownCount = 0,
indexes = [];
function appear(el) {
setTimeout(function() {
var count = 10, i = setInterval(function() {
el.style.opacity = (parseFloat(el.style.opacity) || 0) + 0.1;
if (!count--)
clearInterval(i);
}, 50);
}, shownCount++*200);
}
function shuffle(o){
// from http://stackoverflow.com/questions/6274339/
// how-can-i-shuffle-an-array-in-javascript#answer-6274381
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i),
x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
for (var i = elements.length; i--;) indexes.push(i);
indexes = shuffle(indexes);
for (var f = indexes.length; f--;) appear(elements[indexes[f]]);
}
Upvotes: 1
Reputation: 193291
I would use complete callback of fadeTo
method. Something like this would work:
var spans = $('#changingP span').get();
function fadeIn() {
var index = Math.floor(Math.random() * spans.length);
$(spans[index]).fadeTo(200, 1, function() {
spans.splice(index, 1);
if (spans.length) {
fadeIn();
}
});
}
fadeIn();
span {
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="changingP">
<span>Want </span><span>to </span><span>get </span><span>in</span><span> contact</span><span> with </span><span>me</span><span>?</span>
<br /><span>Email</span><span>: </span><span>edit</span><span>.</span><span>ed</span><span>email</span><span>@</span><span>gmail</span><span>.</span><span>com</span>
<br /><span>Link</span><span>edI</span><span>n</span><span>: </span><span>http</span><span>s://w </span><span></span><span>ww.</span><span>lin</span><span>kedi</span><span>n.com</span><span>/</span><span>in/</span><span>edit</span><span>ed</span><span>email</span>
</p>
Upvotes: 2
Reputation: 1085
Your for loop logic is off. Try this
var maxDelay = 5000;
for(var i=0; i < $length; i++) {
var random = Math.ceil(Math.random() * maxDelay);
$('span')eq(i).delay(random).css("opacity","1");
}
Upvotes: 0