1

I'm trying to animate characters '1-by-1', but i cant seem to figure out, why this code isn't working properly:

$('.overlay-listing').hover(function(){
    var idx = 1;
    $('.strip-hov span', this).each(function(){
        if (!$(this).hasClass('splitrow')){
            setTimeout(function(){
               $(this).toggleClass('animate');
            }, idx * 15);
        }
        idx++
    });
});

I really can't seem to find out whats going wrong. I've also tried to change the "idx * 15" => "idx" like:

$('.overlay-listing').hover(function(){
    var idx = 1;
    $('.strip-hov span', this).each(function(){
        if (!$(this).hasClass('splitrow')){
            setTimeout(function(){
               $(this).toggleClass('animate');
            }, idx);
        }
        idx++
    });
});

The code is working properly without the setTimeout, but then the animation is not what i like it to be. Because it is 'all at once' instead of '1-by-1'.

i've also tried: $(this).delay(xxxx).toggleClass('animate'); to no effect.

2 Answers2

0

I've found it, solution:

$('.overlay-listing').hover(function(){
            var idx = 1;
            $('.strip-hov span', this).each(function(idx){
                if (!$(this).hasClass('splitrow')){
                    var ethis = $(this);
                    setTimeout(function(){
                       ethis.toggleClass('animate');
                    }, idx * 15);
                }
                idx++
            });
        });

the 'this' inside the setTimeout isn't the 'this' i thought it would be. a new function is called so the 'this' changes it's value.

Thanks for you time anyway!

Edit after Marc's comment:

if (!$(this).hasClass('splitrow')){
   setTimeout(function(r){
       $(r).toggleClass('animate');
   }, idx * 15, this);
}

passed it as a param, Thanks for the cleanup!

0

As commented on your solution, here are 2 ways to improve it a litle bit.

Using "this" scope:

$('.overlay-listing').hover(function () {
    var idx = 1;
    $('.strip-hov span', this).each(function (idx) {

        if (!$(this).hasClass('splitrow')) {
            setTimeout(function (scope) {
                $(scope).toggleClass('animate');
            }, idx * 15, this);
        }

        idx++

    });
});

Using "arrow funcions"

$('.overlay-listing').hover(function () {
    var idx = 1;
    $('.strip-hov span', this).each(function (idx) {

        if (!$(this).hasClass('splitrow')) {
            setTimeout(() => {
                $(this).toggleClass('animate');
            }, idx * 15);
        }

        idx++

    });
});

Note, the code is not tested.

Marc
  • 2,920
  • 3
  • 14
  • 30