1

I have a div which I want it to slide from the right of the screen 1 or 2 seconds after the page finished loading.

It seems I cannot achieve this without using the click function. How can I make this work?

2 Answers2

2

Working jsFiddle

Add a callback function for page load:

<body onload="script();">

then add the function:

function script(){
     setTimeout(function(){
         document.getElementById('elementToMove').style.left = '1000px'; // new left position is 1000px in this example
     }, 2000); // 2000 = 2 seconds after page load
}

And don't forget to add CSS3 transition to create the sliding effect

#elementToMove{
  -webkit-transition: left 1s ease;
  transition: left 1s ease;
}
Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
  • Thank you, but I will stick to the CSS3 option that was provided here: http://stackoverflow.com/questions/6805482/css3-transition-animation-on-load/12638711#12638711 –  Apr 03 '16 at 10:38
  • You can stick to any CSS transition you like this is not the critical part of your question... Note that I corrected getElementByID to getElementById. Look at the attached jsFiddle. the problem with having CSS delays is that the page might not have been loaded yet. Using javascript's load function you are sure that the page is fully displayed to the user for 2 seconds before starting the animation – Yotam Omer Apr 03 '16 at 10:42
  • Thank you for the elaborate answer! –  Apr 03 '16 at 10:53
1

This is possible using only CSS animations. Here's an example:

.slidein {
    float:right;

    animation-duration: 5s;
    animation-name: slidein;
}

@keyframes slidein {
    from {
        margin-right: -30%;
    }
    to {
        margin-right: 0%;
    }
}
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141