In my earlier post I showed how to create a simple marquee effect by using a simple JavaScript object. Now it's time to create a vertical marquee using jQuery. This time we're going to use the CSS margin-top
property instead of relative positioning. Our marquee element has been placed within an element with the following CSS declarations:
#container { width: 150px; height: 300px; border: 1px solid gray; overflow: hidden; }
To make the code work it's necessary that the element in question won't have any overflow. Our marquee element, on the other hand, is defined as follows:
#marquee { width: 90%; margin: 0 auto; font: 76% Arial, sans-serif; }
As explained in my previous post, we need two counters, two timers and a final function that creates a timeout that calls itself, thus making the entire animation enter in an infinite loop. Here's the code:
$(document).ready(function() { function runMarquee() { var top = 0; var bottom = 300; var interval = window.setInterval(function() { top += 1; $('#marquee').css('marginTop', top); if(top == 300) { window.clearInterval(interval); var interval2 = window.setInterval(function() { bottom -= 1; $('#marquee').css('marginTop', bottom); if(bottom == 0) { window.clearInterval(interval2); } }, 25); } }, 25); } window.setTimeout(function() { runMarquee(); window.setTimeout(arguments.callee, 15000); }, 25); });
15,000 is the global time requested by the entire animation to complete its run. Note how the first counter has been incremented while the second has been decremented. You can see the demo below.