JavaScript: emulare il tag marquee

JavaScript: emulare il tag marquee

Non può mancare nell'arsenale di uno sviluppatore JavaScript l'emulazione del tag non standard marquee, ossia del testo che scorre ciclicamente da sinistra verso destra (e viceversa). Vediamo come realizzare questo effetto.

Definiamo il seguente oggetto JavaScript:


var Marquee = function(element, width) {
	
	var self = this;

	this.element = document.getElementById(element);
	
	this.width = width;
	
	var limitToRight = this.width;
	var limitToLeft = 0;
	
	var marquee = function() {
	
		var counterTimerToRight = 0;
		var counterTimerToLeft = limitToRight;
		
		var timerToRight = setInterval(function() {
		
			counterTimerToRight += 1;
			
			if(counterTimerToRight == limitToRight) {
			
				clearInterval(timerToRight);
				
				var timerToLeft = setInterval(function() {
				
					counterTimerToLeft -= 1;
					
					if(counterTimerToLeft == limitToLeft) {
					
						clearInterval(timerToLeft);
					
					}
				
					self.element.style.left = counterTimerToLeft + 'px';
				
				}, 25);
			
			}
			
			
			self.element.style.left = counterTimerToRight + 'px';
		
		
		}, 25);	
	
	};
	
	this.run = function() {
	
		var runTimer = setTimeout(function() {
		
			marquee();
			
			setTimeout(arguments.callee, 19850);
		
		
		}, 25);
	
	
	};


};

Questo oggetto fa uso di due timer JavaScript che compiono due operazioni opposte: il primo muove l'elemento verso destra incrementando il suo contatore, mentre il secondo lo muove verso sinistra decrementandolo. Il metodo run() fa entrare i due timer in un ciclo infinito. Il valore 19850 è dato da:

(width * 25) * 2

2 è il numero delle fasi dell'animazione determinato dai rispettivi timer. In questo caso, width è 397:


window.onload = function() {

	var marquee = new Marquee('marquee', 397);
	marquee.run();

};

Per poter funzionare, questo effetto ha bisogno del posizionamento relativo sull'elemento da muovere:


#container {
	width: 430px;
	background: silver;
}

#marquee {
	font-family: Arial, sans-serif;
	position: relative;
}

Potete visionare l'esempio finale in questa pagina.

Torna su