I have been stumped trying to figure out how to integrate a simple for loop to work with the jQuery Cycle plugin. In my basic example I am trying to create 15 cycle functions using jquery .hover() and .cycle().
for(i=1;i<15;i++){
$(".t"+ i).hover(function() {
$('.projectTitle').cycle(i);
});
}
If I create 15 separate functions(per below) the script runs fine but I am in need of simplifying my code.
$('.t1').hover(function() {
$('.projectTitle').cycle(1);
});
$('.t2').hover(function() {
$('.projectTitle').cycle(2);
});
$('.t3').hover(function() {
$('.projectTitle').cycle(3);
});
$('.t4').hover(function() {
$('.projectTitle').cycle(4);
});
...
Any help would be greatly appreciated.
You can circumvent the whole closure issue by storing
ias a data attribute in the DOM element itself:(Incidentally, you should probably replace all those classes with IDs, for performance.)
The “right” way to do this is with a JavaScript closure, which I’m no expert in, but I think should look like this: