Cheesetoast

Brain Food for Web Developers

Arrow

Slide-In jQuery Effect with CSS3

This useful little snippet can be used for making elements slide on from the side of a page as the user scrolls down. It uses jQuery to detect the scrolling point on the page and a CSS3 transition to slide an image in from the right of the screen.

View the demo.

Here’s some simple HTML code that you’d paste below the fold of your page:

<p id="container-paragraph"><img id="trigger_img"src="#"></p>

Here’s the CSS to go with it:

body { width: 800px; } /* This could be any div container */
#container-paragraph { overflow: hidden; } 
/* So that the img is hidden off the side */
.trigger-img {
   position: relative;
   transition: all 1s ease-in-out;
   -moz-transition: all 1s ease-in-out; /* FF */
   -webkit-transition: all 1s ease-in-out; /* Safari & Chrome */
   -o-transition: all 1s ease-in-out; /* Opera */
   left: 1000px; /* More than the width of the body */
}

Now here’s the jQuery code:

$(function() {
   $(window).scroll(function(){
	var distanceTop = $('#container-paragraph').offset().top - windowHeight;

	if  ($(window).scrollTop() > distanceTop){
            $('.trigger_img').css("left", 0);
        }
   });
});

JQuery will slide the image onto the page when you reach the container paragraph. You can adjust the exact point by changing the variable ‘distanceTop’.

It’s tempting to use the jQuery animate function when selecting the trigger_img but typically it’s better to use CSS over jQuery when you can. When jQuery tells the browser to animation something it adds inline styling and increments the values, in this case ‘left’, from 800px to 0.¬†CSS puts the animations in control of the browser, which means better performance.

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.