onsa
12/17/2016 - 12:24 AM

Run a carousel of text spans in a parent element.

Run a carousel of text spans in a parent element.

<!DOCTYPE html>
 <html lang="en-GB">
  <head>
	<meta http-equiv="content-type" content="text/html"; charset="utf-8">
	<script src="jQuery.js"></script>
  </head>
  <body>
	<div ID="slide-text" style="width:80%;margin-left:10%;border:1px solid black;border-radius:4px;overflow:hidden;">	<!-- bordered container to hold text -->
		<div>
			<p>
				<span>Beautiful Railway Bridge of the Silv’ry Tay! </span><span>Alas! I am very sorry to say </span><span>That ninety lives have been taken away </span><span>On the last Sabbath day of 1879, </span><span>Which will be remember’d for a very long time. </span><span>’Twas about seven o’clock at night, </span><span>And the wind it blew with all its might, </span><span>And the rain came pouring down, </span><span>And the dark clouds seem’d to frown, </span><span>And the Demon of the air seem’d to say- </span><span>“I’ll blow down the Bridge of Tay.” </span><span>When the train left Edinburgh </span><span>The passengers’ hearts were light and felt no sorrow, </span><span>But Boreas blew a terrific gale, </span><span>Which made their hearts for to quail, </span><span>And many of the passengers with fear did say- </span><span>“I hope God will send us safe across the Bridge of Tay.” </span>
			</p>
		</div>
	</div>
  </body>
<script>
(function($) {
	/*	(string)'xyz px' ===> (int)xyz	*/
	function pixel_ripper(string){
		return Number(string.substr(0, string.length-2));
	}

	function runny_text() {
		/*	make p element as wide as all the spans together	*/
		var fullWidth = 0;
		$('#slide-text span').each(function(){
			fullWidth += $(this).width()
		})
		$('#slide-text p').width(fullWidth);

		/*	put first span to the right edge of the container	*/
		var offset = $('#slide-text').width();
		$('#slide-text span:first-child').css({'margin-left':offset});

		setInterval(function(){
			/*	animate currently first span 250px to the left	*/
			var textSlider = $('#slide-text span:first-child');
			textSlider.animate({'margin-left':'-=250'}, 5000, "linear");
			/*	if a span is already off the left edge of the container, push the rest back as much as its width,
				then grab it and place it at the end of the queue	*/
			if (pixel_ripper(textSlider.css('margin-left'))*-1 > pixel_ripper(textSlider.css('width'))){
				var offset = pixel_ripper(textSlider.css('margin-left')) + textSlider.width();
				textSlider.next().css({'margin-left':offset});
				textSlider.detach();
				$('#slide-text p').append('<span>'+textSlider.html()+'</span>');
			}
		}, 0);
	}

	$(document).ready(function($) {
		runny_text();
	});
})( jQuery );
</script>
</html>