jQuery: slider automatici ed evento unload

jQuery: slider automatici ed evento unload

Se utilizzate i timer JavaScript per creare slider jQuery automatici avrete sicuramente notato un effetto collaterale che può presentarsi con questo tipo di slider. Quando vi allontanate dalla pagina che contiene lo slider e poi ci tornate su in un secondo tempo, potreste notare che la velocità dello slider è quasi raddoppiata creando così un effetto davvero poco gradevole. Possiamo usare l'evento unload() di jQuery per ovviare al problema.

La documentazione di jQuery afferma che:

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

Presupponendo che il timer JavaScript usato sia accessibile nello scope del nostro codice, possiamo scrivere:


$(window).unload(function() {
				
	clearInterval(timer);
	timer = null;
				
});

In questo modo lo slider non avrà più problemi.

Torna su