Nyxynyx
Nyxynyx

Reputation: 63687

Slide a div off screen (with margin: 0px auto)

I have a horizontally centered div #box1 that has margin: 5px auto that has to slide to the left and off the screen, while #box2 slides into the screen from the right, when the button .class is clicked on. I've seen how its done for absolutely positioned divs, now how do you do it if its not?

HTML Structure

<div class="button"><a href="#">Slide</a> </div>

<div id="container">

    <div id="box1" class="box">Box #1</div>
    <div id="box2" class="box">Box #2</div>

</div>

Failed attempt

$(".button").click(function() {
    $("#box1").css('margin-left', 0);
    $("#box1").css('margin-right', 0);
    $("#box1").animate({
            left: '150%',
        }, 'slow' );

});

Upvotes: 0

Views: 5843

Answers (5)

feskr
feskr

Reputation: 829

This might work for you.

$(".button a").click(function() {

    var $docWidth = $(window).width();
    var $boxOffset = $('#box1').offset();

    $("#box1").css('marginLeft', $boxOffset.left);
    $("#box1").animate({
        marginLeft: $docWidth
    }, 'slow');

});

CSS:

#container: { overflow: hidden; }

http://jsfiddle.net/dZUXJ/

Upvotes: 0

Matthew Darnell
Matthew Darnell

Reputation: 4588

If you needed to, it wouldn't be difficult to absolutely position the element in the same spot it was before animation.

var elm = $("#box1");
var position = elm.position();
var cssObj = {
  'position' : 'absolute',
  'top' : position .top,
  'left' : position.left
}
elm.css(cssObj);

Upvotes: 0

j08691
j08691

Reputation: 207963

Is this the effect you're looking for: jsFiddle example.

jQuery:

$(".button").click(function() {
    $("#box1").css('margin-left', 0);
    $("#box1").css('margin-right', 0);
    $("#box1").animate({ left: '-500px' }, 'slow');
    $("#box2").animate({ left: '0px' }, 'slow');
});​

CSS:

#box1, #box2 {
    margin: 5px auto;   
    border: 1px solid #999;
    position:relative;
}
#box2 {
   left:500px;   
}
#container {
    overflow:hidden;
}

​ HTML:

<div class="button"><a href="#">Slide</a> </div>
<div id="container">
    <div id="box1" class="box">Box #1</div>
    <div id="box2" class="box">Box #2</div>
</div>​

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76890

If you want to slide out a dive you could use jQuery UI hide methods

$(".button").click(function() {
    $("#box1").hide('slide', {
        direction: "left"
    }, 2000);
});

and you can do the same to slide in

$("#box2").show('slide', {
    direction: "left"
}, 1000)

Upvotes: 1

Nemoy
Nemoy

Reputation: 3427

Try

$(".button").click(function() {
    $("#box1").animate({
        marginLeft: '-150%',
    }, 'slow' );

});

Upvotes: 0

Related Questions