Geoff
Geoff

Reputation: 199

jQuery animate back to start after time

I have 3 blocks with images in, overlayed onto this is a transparent screen and a block of text. On a touch device when the user touches the a href link the first time the semi transparent screen and text animate up.

I have this function doing that when checked the user is on a mobile device:

if(isMobile.any())
   $('.animBlock a').on('touchstart', function(e) {
   $(this).filter(':not(:animated)').find('.animTransp').animate({top:"0"}, 300); // animate screen opacity on touch
   $(this).filter(':not(:animated)').find('.animText').animate({top:"30px"}, 300); // animate text on touch
});
;

This works well animating them up on a device such as iPad.

What I'd also like to do is have a timer that then after say 3 seconds if the user has not clicked the link again to go to the page then animate the 2 divs back down to the original position.

Any help really appreciated.

Thanks

Upvotes: 0

Views: 99

Answers (1)

marcjae
marcjae

Reputation: 1410

Add the timeout on one of the completed animations

if (isMobile.any()) {
  $('.animBlock a').on('touchstart', function(e) {

    var animationTrans = $(this).filter(':not(:animated)').find('.animTransp');
    var animationText = $(this).filter(':not(:animated)').find('.animText');

    animationTrans.animate({top:"0"}, 300); // animate screen opacity on touch
    animationText.animate({top:"30px"}, 300, function(){
      setTimeout(function() {
        animationText.animate({top:'-30px'});
        animationText.animate({top:"0"});
      }, 3000);
    });
  });
}

I would however not recommend using jQuery animation for this at all. Rather use css.

<style>
.animTransp { top:-30px; position:relative; transition: top 0.3s;  }
.animTransp.active { top:0; }

.animText { top: 0; position:relative; transition: top 0.3s;}
.animText.active { top:30px; }
</style>

Then your JS would be as follows:

if (isMobile.any()) {
  $('.animBlock a').on('touchstart', function(e) {

    var animationTrans = $(this).find('.animTransp:not(.active)');
    var animationText = $(this).find('.animText:not(.active)');

    animationText.add(animationTrans).addClass('active');

    setTimeout(function() {
      animationText.add(animationTrans).removeClass('active')
    }, 3000);
  });
}

Would probably need to prefix the transition property for webkit mobile

Upvotes: 1

Related Questions