Reputation: 7
I want to stop setInterval() when left margin is 1200px. My code is :-
<html>
<body>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
$('#btn').click(function () {
var i = setInterval(function () {
$('img').animate({
'margin-left': '+=100px'
}, 'fast');
var a = $('img').css('margin-left');
if (a == "1200px") {
clearInterval(i);
}
}, 50);
});
});
</script>
<img src="48_800[1].jpg" height="50px" width="50px"><br>
<input type="button" value="start" id="btn"><br>
</body>
</html>
It is not working.Can anyone help me?
Upvotes: 0
Views: 1847
Reputation: 1321
Use this instead: Updated
$(document).ready(function () {
$('#btn').click(function () {
var i = setInterval(function () {
$('img').animate({
'margin-left': '+=100px'
}, 'fast');
var a = $('img').css('margin-left');
//console.log(a.substring(0,a.lastIndexOf('px')));
if (a.substring(0,a.lastIndexOf('px')) >= 1200) {
clearInterval(i);
}
}, 50);
});
});
Upvotes: 1
Reputation: 41595
You should cast to an integer the pixels value a = parseInt(a);
. (as before you were obtaining values of margin-left
with decimals, such as 99.45px
and then 199.45px
so it was jumping the 100px
)
var i = setInterval(function () {
$('img').animate({
'margin-left': '+=100px'
}, 'fast');
var a = $('img').css('margin-left');
a = parseInt(a);
if (a >= 100) {
clearInterval(i);
}
}, 50);
Update
Note that in the examples I'm using >=100
to see the results.
Upvotes: 3
Reputation: 340
try to change the value for the time into the setInterval method
the number value must to be in milliseconds
Upvotes: 0
Reputation: 6002
$(document).ready(function () {
$('#btn').click(function () {
var a="";
while(a != "1200px"){
$('img').animate({
'margin-left': '+=100px'
}, 'fast');
a = $('img').css('margin-left');
}
});
});
your existing code looks erroneous ,besides referring to SetInterval
is not required, the same could be achieved with decent while clause itself.
happy Coding :)
Upvotes: 0