Move a sentence 20px every 3 seconds with setInterval

Viewed 829

I'm trying to simply move a sentence 20px on the y-axis every 3 seconds by using setInterval(). My code will only move the sentence one time. What's going on?

var yAxis = 20;

setInterval(function() {
    $('.sentence').css('transform', 'matrix(1, 0, 0, 1, 0,' + yAxis + ')');
 }, 3000);

fiddle

3 Answers

You can use offset() method to get offset of current element from left and from top. At first, get current offset from top and then override it with new value, which will be "oldOffset + 20px" in your case. Here is the working example:

setInterval(function() {
    var el = $('.sentence');
    var currentOffset = el.offset();
    el.offset({ top: currentOffset.top + 20, left: currentOffset.left})
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="sentence">Text Text Text</p>

The CSS directive you give is always the same - transform .sentence from its original position to 20points lower.

Use:

var yAxis=0;
setInterval(function() {
$('.sentence').css('transform', 'matrix(1, 0, 0, 1, 0,' + (yAxis+=20) + ')'); }, 3000);

instead

Your transform does not add 20 to the existing Y. It simply sets the Y to 20. You need to store the state of the previous transformation then update that value before applying it to the next transform.

let yAxis = 0;

setInterval(function() {
  yAxis += 20;
  $('.sentence').css('transform', 'matrix(1, 0, 0, 1, 0,' + yAxis + ')'); 
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sentence">This is a sentence.</div>

Related