-1

this function changes the classes of my links to change color when i hover on them, but they only change once when i hover. how can i make it so while i'm hovering the class keeps changing?

<script type="text/javascript">
        $(".nav a").hover(function(e){
            var randomClass = getRandomClass();
            $(e.target).attr("class", randomClass);
        });
        $(".text a").hover(function(e){
            var randomClass = getRandomClass();
            $(e.target).attr("class", randomClass);
        });
    function getRandomClass(){
        var classes = new Array("green", "purple", "teal", "violet", "pink", "red", "yellow", "blue", "magenta", "orange");
        var randomNumber = Math.floor(Math.random()*11);
        return classes[randomNumber];
    }
    </script>

thanks

3 Answers3

1

You can add a setInterval.

Like this:

var textInterval;

$(".text a").hover(function(e) {
  var evt = e;
  textInterval = setInterval(function() {

    var randomClass = getRandomClass();
    $(evt.target).attr("class", randomClass);

  }, 200); //change 200 for the timing you want the interval to repeat in ms 
}, function(e) {
  //clear interval when uses moves mouse away
  clearInterval(textInterval);
});
Joel Almeida
  • 7,939
  • 5
  • 25
  • 51
0

If you want to keep changing the class while you're moving mouse hover the link, you can just change the event "hover" to the "mousemove":

https://api.jquery.com/mousemove/

If you want to change class while you're hovering the link but not moving the mouse, you can set a interval to keep changing:

jQuery - How can I continue an animation while the mouse hovers over an element?

Community
  • 1
  • 1
Ricardo Pontual
  • 3,749
  • 3
  • 28
  • 43
0

Check below jsFiddle link

Fiddle

$(".text a").hover(function(e) {
    var evt = e;
    textInterval = setInterval(function() {

        var randomClass = getRandomClass();
        $(evt.target).attr("class", randomClass);

    }, 10); //change 200 for the timing you want the interval to repeat in ms 
}, function(e) {
    //clear interval when uses moves mouse away
    clearInterval(textInterval);
    var randomClass = getRandomClass();
    $(e.target).attr("class", randomClass);
});

function getRandomClass() {
    var classes = new Array("green", "purple", "teal", "violet", "pink", "red", "yellow", "blue", "magenta", "orange");
    var randomNumber = Math.floor(Math.random() * 11);
    return classes[randomNumber];
}
Community
  • 1
  • 1