Home > Javascript > Custom animation using jCarousel and jQuery

Custom animation using jCarousel and jQuery

Yet another javascript demo, this time using jQuery. For those of you who haven’t worked or heard of jQuery here’s a quick explanation taken from their website: jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.. So, first thing you need to do is go to jquery.com and download the latest version if the library.

Next thing that you need is the jCarousel plugin, written by Jan Sorgalla – visit http://sorgalla.com/projects/jcarousel/ for more details.

Dont want to read everything? You can view the online demo or jCarousel Animation (2184 downloads)

Now you’re able to add carousel effects to both vertical lists and horizontal lists. I guess 90% of the time, jCarousel is flexible enough and will let you customize a lot of things from styles to behavior. However, today I wanted to add an effect to a list and I couldn’t make the plugin work as needed. Maybe I missed something, but anyway, here’s an example on how to change the default animations for jCarousel.

First, here’s the effect I wanted: on a horizontal carousel, elements auto scroll to the right until they reach the end, then change scroll to the left until they reach the start element. Let’s call this a variant of the circular wrap that can be defined with jCarousel.

Let’s setup the carousel – include style sheets and javascripts:

<link type="text/css" rel="stylesheet" href="res/jcarousel/jquery.jcarousel.css" media="screen" />
<link type="text/css" rel="stylesheet" href="res/jcarousel/skins/ie7/skin.css" media="screen" />

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="res/jcarousel/jquery.jcarousel.pack.js"></script>
<script type="text/javascript" src="js/pcarousel.js"></script>

then create the carousel markup:

<div class="pCarouselWrapper">
<div class="controls">
	<a href="#" class="pCarouselPrev">&laquo; prev</a>
	<a href="#" class="pCarouselStop">stop animation</a>
	<a href="#" class="pCarouselStart">start animation</a>
	<a href="#" class="pCarouselNext">next &raquo;</a>
</div>
<ul id="pCarousel" class="jcarousel-skin-ie7">
  <li>item data 1</li>
  <li>item data 2</li>
  <li>item data 3</li>
...
  <li>item data n</li>
</ul>
</div>

I’ve added my own controls for prev() and next(), as well as a way to stop & start the animation. Now let’s configure the carousel:

jQuery(document).ready(function() {
  jQuery('#pCarousel').jcarousel({
    wrap: 'left',
    scroll: 1,
    visible: 3,
    initCallback: pCarousel.init,
    easing: 'linear',
    animation: pCarousel.animationSpeed,
    buttonPrevHTML: null,
    buttonNextHTML: null
  });
});

Some quick comments, on the outcomes – shows 3 elements at once, scrolls only one each time, the movement effect is using linear easing (check out jQuery manual for more info on this) and default jCarousel control buttons are disabled. Everything is initialized via the pCarousel.init callback.

The effect is done by the pCarousel object:

var pCarousel = {
	animationId: null,
	animationDir: 'right',
	
	//time in miliseconds to wait before scrolling
	animationTimeout: 3000,
	
	//time in miliseconds for the scrolling transition
	animationSpeed: 250,
		
	init: function(carousel) {
		// Disable autoscrolling if the user clicks the prev or next button.
		carousel.clip.hover(function() { pCarousel.halt() }, function() { pCarousel.animate(carousel); });
		pCarousel.animate(carousel);
		
		jQuery('a.pCarouselNext').bind('click', function() {
			pCarousel.halt();
		        carousel.next();
			return false;
    		});
		
		jQuery('a.pCarouselPrev').bind('click', function() {
			pCarousel.halt();
			carousel.prev();
			return false;
		});
		
		jQuery('a.pCarouselStop').bind('click', function() {
			pCarousel.halt();
			return false;
		});
		
		jQuery('a.pCarouselStart').bind('click', function() {
			if( pCarousel.animationId ) { //already running
				pCarousel.halt();
				carousel.scroll(1);
				pCarousel.animationDir = 'right';
			}

			pCarousel.animate(carousel);
			return false;
		});
	},
	
	animate: function(carousel) {
		pCarousel.animationId = setInterval( function() {
			if( carousel.last == carousel.options.size ) { pCarousel.animationDir = 'left'; }
			else if( carousel.first == 1 ) { pCarousel.animationDir = 'right'; }
	
			if( pCarousel.animationDir == 'right' ) { carousel.next(); }
			else { carousel.prev(); }
		}, pCarousel.animationTimeout );
	},
	
	halt: function() {
		if( pCarousel.animationId ) {
			clearInterval(pCarousel.animationId);
		}
	}
	
};

Again, a few explanations – there are three methods, animate(), halt() and init(). Inside init(), we’re adding listeners on DOM elements and also a pseudo-listener (via the carousel object) that freezes animation while hovering the mouse over a list item.

The halt() method simply stops the current animation, by clearing the interval. Once again setInterval comes to the rescue!

The entire animation is handled by a setInterval() call, running the animation algorithm at specific intervals – the time that you want to keep the information on the screen (in this case, it’s 3 seconds). Then, the trick is to set a scrolling direction and change it each time the carousel reaches an end. By looking at the direction, you can either call next() or prev().

Nothing fancy, nothing new, but I think it’s a nice and useful animation.

Demo | jCarousel Animation (2184 downloads)

  1. Cristi
    | #1

    i think you can do some math with the js and adjust the width/heights, but I’d probably use something else… keep in mind, this article is 5 years old and RWD was in its early stages at that time. i’ve used this plugin with success, i think it has everything you need: http://dev7studios.com/plugins/caroufredsel/, but i see it’s not free anymore.

  2. poorna
    | #2

    Hi, It is awesome plugin. It works perfectly. But I need responsive for that images. Can anyone please tell how to make it responsive. I tried media query also, but it wont accept. It will take the width of the li from the script. How can I change this? Thanks in advance..

  3. | #3

    Hey Cristi, thanks so much for this! Exactly what I needed (more control over jCarousel), plus your code is simple and clean, even I can understand it! Thanks again so much!

  4. Cristi
    | #4

    There’s no js error on FF, however it’s not functioning properly – this demo is not meant to be used with circular wrap if I remember correctly.

  5. | #5

    nice articles, but i have error on file dk.carousel.js, if i setting like this :
    jQuery(document).ready(function() {
    jQuery(‘#pCarousel’).jcarousel({
    wrap: ‘circular’,
    scroll: 3,
    visible: 3,
    initCallback: pCarousel.init,
    easing: ‘linear’,
    animation: pCarousel.animationSpeed,
    buttonPrevHTML: null,
    buttonNextHTML: null
    });

    note : wrap: ‘circular’

    the slide error on safari in windows,

  6. Cristi
    | #6

    All you need to do with the current setup is use pCarousel.animationDir = ‘left’; or pCarousel.animationDir = ‘right’; So, on your buttons you would add an onclick event and add set the animationDir.

  7. Roj
    | #7

    Hi,
    I have implemented the circular carousel setting up the auto functionality from the mentioned link above http://sorgalla.com/projects/jcarousel/examples/static_circular.html.
    Now, I am not being able to have two buttons: one when clicked will change the scrolling direction to right and another will change the scrolling direction to left. I tried to modify the code but as I m not good with jquery, was not successful.
    Help will be much appreciated and Thanks for this post as well.. get a chance to learn something..

  8. Cristi
    | #8

    Of course it is possible – just remove the markup for the controls and the listeners from the javascript code and you should be set. Oh and you might want to force jCarousel to do a circular animation. But once again, if I understand correctly what you want to achieve, there’s no need for this custom animation, all you need is jCarousel with proper setup. Cheers!

  9. Makanti
    | #9

    Hi again Christi and thanks for your response.
    I thought I could combine the wrap ‘circular’ with your carousel keeping just the auto scrolling and not the controllers you have. Do you think this is possible? Thanksss

  10. Cristi
    | #10

    I think you want a circular carousel, and that’s already implemented in jCarousel – http://sorgalla.com/projects/jcarousel/examples/static_circular.html

  11. Makanti
    | #11

    Hello there!
    I really enjoyed your tut and ended up to use it somehow as a simple auto scrolling carousel without controllers. The only thing I would like to achieve is to mg oake the autoscrollinnly from right to left. So every time it reaches the last image the next one becomes again first and so on. Any good ideas about that? I tried several things but nothing worked out:( thanks a lot and great work again! thumbs up!:)

  12. Rahul
    | #12

    Hi Christi,

    Thanks a lot for your reply, provided information is very helpful.
    thanks again, but i would like to share my implementation also
    what i hav done is, i have put one condition in which i am checking (document.getElementById(“”).complete==true)
    then execute the functionality.

    Thanks again christi

  13. Cristi
    | #13

    you should somehow handle the image.onload event for each of your image. so the startCarousel would only trigger when all images have finished loading.
    another option would be to bind the start of the carousel to the load event of the document, rather than the ready state – instead of $(document).ready(function() {}), use $(document).load() – not recommended, but should do the trick.

  14. Rahul
    | #14

    Hey guys,

    I like the post, thanks for great help.
    I have one doubt please help me, in my case through JCarousel there is one animation on the home page of my website.

    Animation is : there are heavy heavy images which will loaded and scroll automatically in the direction left to right (Kind of sliding effect).
    now problem is when images are loading(means half loaded) then by that time image get’s slide from left to right, which is not good.

    It should be like once loaded completly then starts sliding effect

    I hope what i have written above is understanble

    Thanks in advance

  15. salim
    | #15

    Hi,

    I actually tried on my mac safari(v 3.1) although it works on my windows safari(4.0.2).

    i think it’s the issue with jquery(1.3.2) and the jcarousel if we use the older jquery (1.2.3 ) it does work.

  16. Cristi
    | #16

    hey salim, thanks for the feedback – i just tested it on safari for windows and indeed it doesnt work – actually it only works if you click on the “start animation” button. strange indeed. i’ll try to debug it and post some updates.

  17. salim
    | #17

    Hi,
    Great work..
    just one glich doesn’t work in safari with mac. it doesn’t scroll at all
    any idea?
    regards
    salim

  18. Cristi
    | #18

    hey vinod, thank for the appreciation. i’m not sure i understand correctly, but you could add the description in a div tag (add styling + display: none), then whenever an event occurs (like image click, image hover, button click), show this div. you could even style it to overlay the entire description over the image 😉

  19. vinod
    | #19

    wow! nice post.

    i would like to customize it.

    so that when i click the image or arrow, i need to show the image description below it.

    how to do this?

  1. No trackbacks yet.