1

This is my code. It works on first click but not on second.. More precisely, IF works, ELSE doesn't work.

$(document).ready(function(){
    $( ".one" ).click(function() {     
        if($('.two').css('margin-right','-345px'))
            $('.two').css('margin-right', '0');
        else
            $('.two').css('margin-right', '-345px');       
    });
});

What am I doing wrong?

hiru
  • 153
  • 1
  • 7
  • 1
    You want to compare the css property with that value (-345px), but this is the syntax to set the css property. – grdevphl Jun 11 '15 at 17:52

3 Answers3

0
$(document).ready(function(){
    $( ".one" ).click(function() {     
        if($('.two').css('margin-right') === '-345px')
            $('.two').css('margin-right', '0');
        else
            $('.two').css('margin-right', '-345px');       
    });
});
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

Your condition is not correct.

It should be:

if($('.two').css('margin-right') == '-345px')
    ....
codingrose
  • 15,563
  • 11
  • 39
  • 58
0

Why not simplify things:

JS:

$(document).ready(function(){
    $( ".one" ).click(function() {     
        $('.two').toggleClass('mymargin');
    });
});

And CSS

.mymargin{
    margin-right:-345px;
}
Ted
  • 14,757
  • 2
  • 41
  • 58
  • I didn't want to edit CSS so I decided to do everything in jQuery, but I'll probably use your method in the future. It is really simple – hiru Jun 11 '15 at 17:58