Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios-like animation to slide content from right to left

I am trying to emulate an effect I have seen on numerous iPhone applications. It essentially slides the content on the screen from right to left when a button is clicked. The content from the original screen slides out of view to the left, and the content for the next screen slides into view from the right to the center.

I have been able to essentially emulate this with jQuery. See this fiddle. It works fine, but as the animation becomes more complex (i.e. adding buttons to revert to the original screen or when there are more than two screens) this method becomes very complex and confusing. I am sure there is a more efficient way to achieve this effect, but I don't know it. Can someone give me a hint? I have searched the web, but I do not think I am using the correct terms in my search because I haven't found anything. My code is shown below.

HTML:

<div id="screen1">
    <div id="header">Screen 1</div>
</div>

<div id="screen2">
    <div id="header">Screen 2</div>
</div>

<a href="#" id="button">Swipe</a>

CSS:

body, html {
    width: 100%;
    height: 100%;
}

#screen1 {
    background: blue;
    width: 100%;
    height: 100%;
    position: fixed;
}

#header {
    height: 50px;
    width: 100%;
    background: red;
}

#screen2 {
    background: green;
    width: 0px;
    height: 100%;
    position: fixed;
    right: 0;
}

jQuery:

$('#button').click(function(){
    $('#screen1').animate({width: '0px'});
    $('#screen2').animate({width: '100%'});
});

JS Fiddle Example

like image 257
JSW189 Avatar asked Jan 23 '26 06:01

JSW189


1 Answers

I don't see anything wrong with what you are currently doing. One improvement you could make is only animate one element when switching screens. For example, give #screen1 z-index: 1 and #screen2 z-index: 2. Then you can remove the line that animates #screen1 because the other screen will appear on top of it. jsFiddle example

If you have multiple screens, you can start all the screens with z-index: 0. When you want a screen to appear on top, give it z-index: 1 first, then perform the animation to put it on top of the other screens. When doing this again with yet another screen, you can do the same thing and switch the z-indexes before the animation. You would also need to set the width appropriately as well. In the end, your JS might look something like this:

$targetScreen = getTargetScreen(); // somehow figure out which screen you're switching to
$prevTargetScreen = getPrevTargetScreen(); // this will also depend on your implementation

$prevTargetScreen.css('z-index', 0);
$targetScreen
    .css({ width: 0, `z-index`: 1 })
    .animate({width: '100%'});
like image 181
Zhihao Avatar answered Jan 24 '26 18:01

Zhihao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!