jquery onclick add margin-left

26,705

Solution 1

add an = in front of your value:

$(function() {
    $('#next_nav').click(function() {
       $('#nav').css('margin-left', '-=10px');
    });
});

Working Fiddle

EDIT

If you want to animate it, use animate() method. Here is a fiddle for you.

Solution 2

Check on jsFiddle

   $(document).ready(function (){
       $("#next_nav").on("click", function() {
          var $left = $("#nav").css('margin-left');
          var $newval = (parseInt($left) - 10) + "px";
          $("#nav").css ({
            'margin-left' : $newval
          });
       });
   });

Solution 3

You can try this

var pixels=0;
$(function() {
    $('#next_nav').click(function () {
       pixels=pixels-10;      
       $( "#nav" ).css('margin-left',pixels);
    });
});

Working fiddle is available here.

Share:
26,705
mmdwc
Author by

mmdwc

Updated on July 29, 2020

Comments

  • mmdwc
    mmdwc almost 4 years

    I'm trying something pretty simple in JS but I can't make it work...

    I would like when clicking on a div to add a negative margin-left to another div, but I want it to happened everytime I click on the div, not only one time as it does now. Eveytime I click on my #next_nav, I would like the #nav to move from 10px negative. here it only works one time. here is my js :

    $(function() {
      $('#next_nav').click(function () {
         $( "#nav" ).css('margin-left','-10px');
      });
    });
    

    and my HTML :

    <div id="next_nav"></div>
    <div id="nav"></div>
    

    here is my JSfiddle : http://jsfiddle.net/Beyzd/

    can anybody helps me with this ? thanks a lot,

  • mmdwc
    mmdwc over 10 years
    is it possible to add animation to make it move ? like .animate slow ?
  • mmdwc
    mmdwc over 10 years
    thanks @AloneInTheDark, but in your fiddle the margin is not 10px, and when clicking again on the #next_nav, my nav takes its initial position, do you know why ?
  • AloneInTheDark
    AloneInTheDark over 10 years
    Because there is a "toggle" value in the function. Toggle means, a property can be on/off with an action event. You can change this value (i don't remember how to disable right now). I guess there is no parameter like "margin" in animate() function. You can read some documents about it.