Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

How to make a div's marginLeft increment through button clicks

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.

http://jsfiddle.net/9KgjQ/

$( "#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

Answers (3)

Anand Jha
Anand Jha

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');

   });

});

New Working demo

Upvotes: 2

ebi
ebi

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

codingrose
codingrose

Reputation: 15709

Try:

$(function() {
  $( "#move" ).on( "click", function() {
      $( ".test" ).animate({
          "margin-left":"+=50px"
      });
   });

});

DEMO here.

Upvotes: 2

Related Questions