Reputation: 20007
I am trying to play around with jQuery and was wondering how I can acheive the following situation:
You have a button and a div.
<div class="test"></div>
<button id="move">Move</button>
You click the button, and the div's marginLeft gets incremented by 50px.
I have made the following jsFiddle that works for the first click, but not for any subsequent clicks.
$( "#move" ).on( "click", function() {
$( ".test" ).css({
marginLeft: function( margin, value ) {
margin += 50;
value = margin + "px";
return value;
}
});
});
How can this be done?
Upvotes: 0
Views: 112
Reputation: 10724
Try this,
$(function() {
$( "#move" ).on( "click", function() {
var mleft= $( ".test" ).css('margin-left');
mleft=mleft.split('p')[0]-0;
var newMargin=+mleft+50;
$( ".test" ).css('margin-left',newMargin+'px');
});
});
Upvotes: 2
Reputation: 118
Your marginLeft function has the wrong parameters. The first one is the index while the second one is the current value. So you could do this:
$(function() {
$( "#move" ).on( "click", function() {
$( ".test" ).css({
marginLeft: function( index, margin ) {
margin = parseInt(margin, 10) + 50;
value = margin + "px";
return value;
}
});
});
});
Upvotes: 4
Reputation: 15709
Try:
$(function() {
$( "#move" ).on( "click", function() {
$( ".test" ).animate({
"margin-left":"+=50px"
});
});
});
Upvotes: 2