Richard Richard - 1 year ago 102
HTML Question

text animate on mouseover, stop and reset on mouseout

I am looking to have some text that is static, but when a user hovers over the text, it animates through an array of different words, stopping and showing the static word when the user removes their mouse.

I got pretty far with the help of this other SO post:

changing text periodically in a span from an array with jquery

But cant get the loop queue to stop and go back to the original word after the hover is removed.

I want to have a sentence, such as this:

<p>Here is a sentence <span id="rotate">this</span> is what changes</p>

So that if the user hovers over "this", then it animates by fading in/out to an array of other words, eg:

var terms = ["newword1", "newword2", "newword3"];

But when the hover is removed, it then stops the animation queue and resets to show "this" again.

This is what I have so far:

var terms = ["term 1", "term 2", "term 3"];

function rotateTerm() {
var ct = $("#rotate").data("term") || 0;
$("#rotate").data("term", ct == terms.length -1 ? 0 : ct + 1).text(terms[ct]).fadeIn()
.delay(2000).fadeOut(200, rotateTerm);

Mainly from the other SO post, but have changed the trigger to:



So this now fires on mouseover, which is great, but I have difficulty in what to put in the "mouseleave" function to stop the rotating text that is now running all the time.

Answer Source

I think you're looking for something like this:

var terms = ["term 1", "term 2", "term 3"],

function displayNext() {
  var ct = $("#rotate").data("term") || 0;
  setTimeout(function() {
    $("#rotate").data("term", ct == terms.length - 1 ? 0 : ct + 1).text(terms[ct]).fadeIn();
  }, 190);

function rotateTerm() {
  interval = setInterval(function() {
  }, 2000);

$("#rotate").mouseenter(function() {

$("#rotate").mouseleave(function() {
  setTimeout(function() {
  }, 200);

Working Fiddle: here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download