-1

I have this code for sliding elements from the left.

$(".slide-left")
   .css("margin-left",-$(this).width())
   .delay(400)
   .animate({
       marginLeft:0
 }, 900);

However when I try from the right, nothing happens! It seems logical code, what I am clearly missing here?

$(".slide-right")
   .css("margin-right",-$(this).width())
   .delay(400)
   .animate({
   marginRight:0
}, 900);
Tepken Vannkorn
  • 9,648
  • 14
  • 61
  • 86

4 Answers4

0

It's difficult to give an exact answer without the rest of the code but I would suggest using margin left to animate right as well.

$(".slide-right")
   .css("margin-left",0)
   .delay(400)
   .animate({
   marginLeft:$(this).width()
}, 900);

JS Fiddle: http://jsfiddle.net/JBgLc/1/

heardy
  • 54
  • 4
0

margin-right only has an effect on elements surrounding or near .slide-right. Basically, you wouldn't see what's going on unless you had other elements to the right of it. However, it is important to note that this will have no effect on .slide-right itself, just the surrounding elements. This can be better understood by looking at a demo with display:inline;:

DEMO: http://jsfiddle.net/dirtyd77/74JtL/

A better way to go about this would be using right instead of margin-right, however, you would also need to use position:

$(function(){
    $(".slide-right")
   .css("right",$(this).width())
   .delay(400)
   .animate({
   right:0
}, 900);
});

DEMO: http://jsfiddle.net/dirtyd77/74JtL/2/

Dom
  • 38,906
  • 12
  • 52
  • 81
0

Using a negative margin-right often doesn't work -- it's better to use a positive margin-left instead because the margin-right only applies to objects following: it does not affect the location of the object it is assigned to.

Use:

.css("margin-left",$(this).width())

instead of:

.css("margin-right",-$(this).width())

See this JSFiddle.

Robbie Wxyz
  • 7,671
  • 2
  • 32
  • 47
0

Because the code is somewhat general, yet there is a desire for a CSS animation solution, I attached the animation using a check box instead of jQuery. You can change the direction of the slide by adding a negative to the margin-left attribute in the keyframes. I only set this up for webkit, but it can easily be extended to other browsers.

CSS:

input[type="checkbox"]:checked + .slide-right{
-webkit-animation-delay:400ms;
-webkit-animation: slider 900ms; 
}

div{
 width:50px;
 height:50px;
 border:1px solid black;
}

@-webkit-keyframes slider{
 100%{margin-left:400px;}
}

http://jsfiddle.net/rfWtD/

Conqueror
  • 4,265
  • 7
  • 35
  • 41