I’m doing a simple animation by click a box to move to the right by 100px on each click. And I want that when its position reaches 400, it should move to the left by 100px on each click.
I did a console.log() but the console only show the initial positioning of the element, and it doesn’t update after each click.
I also want the final position to show on the <span id="info"> but it also doesn’t update.
Why is that?
Many Thanks
jquery:
$('#somebox > a').click(function(e){
var thisElem = $(this),
aPos = thisElem.position();
thisElem.animate({ marginLeft: '+=100px' });
if(aPos.left === 400){
thisElem.animate({ marginLeft: '-=100px' });
}
console.log('finish pos: ' + aPos.left);
$('#info').text(aPos.left + 'px');
e.preventDefault();
});
HTML:
<div id="somebox">
<a href="#">show</a>
<span id="info">10px</span>
</div>
CSS:
#somebox{
position: relative;
background: #EEF0EB;
border: 1px solid #dedbd7;
height: 300px;
width: 500px;
}
#somebox a{
display: block;
color: #fff;
font-weight: bold;
border: 1px solid #099;
background: #0C9;
padding: 5px;
width: 50px;
text-decoration: none;
}
#info{
display: block;
font-size: 36px;
color: #777;
font-weight: bold;
width: 100px;
margin: 100px auto;
}
How about using the
.data()method to make your life easier?DEMO