Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS animation : move a div with the new position relative to the previous

for better performance, I want replace:

$('#foo').animate({ left: '+=42px' }, 500);

by a transition (or animation) CSS3. But how can we do to implement "+=" on left property in CSS?

How move a div with the new left position relative to the previous?

thx.

like image 790
Matrix Avatar asked Jan 09 '23 17:01

Matrix


2 Answers

In vanilla-js you can't use +=, but you can get the old value instead:

document.getElementById('foo').onclick = function() {
  this.style.left = parseFloat(getComputedStyle(this).left) + 42 + 'px';
};
#foo {
  position: relative;
  left: 0;
  transition: 2s left;
}
<div id="foo">Click me multiple times</div>
like image 137
Oriol Avatar answered Jan 12 '23 09:01

Oriol


You can use the transition for smooth animation. you just put transition settings in the CSS of an element like this,

#foo {
    -webkit-transition: all 0.5s ease-out;
    -o-transition: all 0.5s ease-out;
    -moz-transition: all 0.5s ease-out;
    transition: all 0.5s ease-out
}

Then do your incrementation of left with script like this.

$('#foo').css('left', '+=42px');

You can refer to this page.

like image 24
hitesh upadhyay Avatar answered Jan 12 '23 09:01

hitesh upadhyay