Simple jquery rotator

Sometimes we just want a few lines of code to do a small task. Jquery is perfect for this. Instead of embedding loads of plugins increasing download times, we should just do something simple. Below is a simple rotator:

/* rotator */ function start_rotating() { var total_elements = $('#testimonials > div').length; var starting_number = Math.ceil(Math.random() * total_elements); $('#testimonials > div').hide(); $('#testimonials >div:nth-child(' + starting_number + ')').show() .addClass('active'); show_timer1 = setTimeout(function(){continue_rotating()}, 5000); } function continue_rotating() { var element = $('#testimonials > div.active').next(); if ($(element).parent().attr('id') != 'testimonials') { element = $('#testimonials > div:first'); } $('#testimonials > div.active').hide().removeClass('active'); $(element).fadeIn().addClass('active'); show_timer1 = setTimeout(function(){continue_rotating()}, 5000); } if ($('#testimonials').length) { start_rotating(); }

The above code consists of very few lines of code therefore making it a lot easier to change and manipulate for your own needs. Keeping a library of small usable snippets will guarantee projects finish on time and within budget. The other benefit is that you'll most likely understand every line and what it does and this allows finding bugs and updating a much simpler task.