Question

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,

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Fixed it for you: Updated version

edit the .css('margin-left','-10px'); to .css({'margin-left' : '-10px'});

Try this:

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

Working Fiddle

just change this $( "#nav" ).css('margin-left','-=10px');

$(function() {
  var count=0;
  $('#next_nav').click(function () {
  count-=10;

$( "#nav" ).css('margin-left',count);
});
});

And include jQuery

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top