Reputation: 11
In the below piece of code I tried to make the objects with class "rot" to change the inner HTML by using the value attribute that includes an array of chars.
I want that this characters will rotate with an interval.
I noticed that the problem is in the inner for loop - I need there a setTimeout or something like this but it doesn't work.
any solution for this problem?
Thanks in advance.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<span class="rot" value="$^%^@">currency</span>
<span class="rot" value="1^2^3">numbers</span>
<script>
function rotateItem()
{
for(j=0;j<$(".rot").get().length;j++)
{
valueToRotate = $(".rot:eq("+j+")").attr("value").split("^");
for(i=0;i<valueToRotate.length;i++)
{
$(".rot:eq("+j+")").html(valueToRotate[i]);
}
}
}
setInterval("rotateItem()",1000)
</script>
Upvotes: 1
Views: 259
Reputation: 567
You can use the jQuery .data() method to store the current index of each character being rotated. Also, the .each() method makes it very easy to perform some function for each element in a jQuery result.
Try this:
function rotateItem() {
$('.rot').each(function() { // for each jquery object with class 'rot'
var values = $(this).attr('value').split('^'); // get value array
if ($(this).data('activeVal') == null) // if 'activeVal' is not set, set it to a default of 0
$(this).data('activeVal', 0);
else // otherwise increment through array indexes
$(this).data('activeVal', ($(this).data('activeVal') + 1)%values.length); // mod (%) makes sure we loop back when we get to the end
$(this).html(values[$(this).data('activeVal')]);
});
}
setInterval(rotateItem,1000);
Upvotes: 1