MindX MindX - 8 months ago 32
HTML Question

How to return original inner text on mouseleave?

I would like to randomize characters on hover for a specific id.
It works fine on mouse enter but can't get it stop and back to initial text when mouse leave.

Here's the code.



jQuery(function($) {
function text_shuffle() {
"use strict";
var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var $_inter = setInterval(function() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}, 100);
}
$("#text-shuffle").mouseenter(text_shuffle);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>





Thanks for your help

aje aje
Answer Source

Use clearInterval to stop the randomize characters, replace the original text when mouse goes out of text.

jQuery(function($) {
function text_shuffle() {
    "use strict";
    var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
     $_inter = setInterval(function() {
        var text = document.getElementById("text-shuffle");
        text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
        counter = (counter+1)%text.innerHTML.length;
    }, 100);
}
var value, $_inter;
$("#text-shuffle").mouseenter( function(){
   value  = $(this).html();
  text_shuffle();
  }).
  mouseout(function(){
  clearInterval($_inter);

    $(this).html(value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>