1

I have javascript that when hover plays an animation, but i have 4 different animations and i would like it to randomize it each time the element is hovered over

here's my code

function firsthelp() { 

document.getElementById('help-text').innerHTML = 'Enter your first name';
  document.getElementById('help-box').style.animation ='greenhover 2s;';
  document.getElementById('help-box').style.WebkitAnimation ='greenhover 2s';


}

The other css animations are bluehover orangehover and purplehover

4 Answers 4

2
    function getRandomAnimation(duration) {

      var possibleAnimations = ["greenhover","bluehover","orangehover","purplehover"];
      var randomNumber = Math.floor((Math.random()*4));
      return (possibleAnimations[randomNumber] + " " + duration || "");
    }

and use it like this:

  document.getElementById('help-box').style.animation = getRandomAnimation('2s)';
Sign up to request clarification or add additional context in comments.

Comments

1

Use Math.random to randomize your animations

var randomNumber = Math.floor((Math.random()*4)+1);
var hover;
if(randomNumber == 1)
{
    hover = 'greenhover'
}
else if(randomNumber == 2)
{
    hover = 'purplehover';        
}
else if(randomNumber == 3)
{
    hover = 'orangehover';        
}
else if(randomNumber == 4)
{
    hover = 'bluehover';        
}

document.getElementById('help-text').innerHTML = 'Enter your first name';
document.getElementById('help-box').style.animation =hover +' 2s;';
document.getElementById('help-box').style.WebkitAnimation =hover +' 2s';

Comments

0
function firsthelp() { 

document.getElementById('help-text').innerHTML = 'Enter your first name';
  var random_animation = ["greenhover", "bluehover", "orangehover", "purplehover"];
  var number = Math.random();
  var animation = random_animation[Math.floor(number * 4)] + " 2s";
  document.getElementById('help-box').style.animation = animation;
}

Comments

0

You can use Math.Random to get random no between 1 to 4 or either 0 to 3. Here I am getting between 0 to 3 and using a JavaScript array to get the animation

var animations = new Array();
animations[0] = "greenhover";
animations[1] = "bluehover";
animations[2] = "orangehover";
animations[3] = "purplehover";

var randomNo = Math.floor(Math.random() * 4);

document.getElementById('help-text').innerHTML = 'Enter your first name';
document.getElementById('help-box').style.animation =animations[randomNo] +' 2s;';
document.getElementById('help-box').style.WebkitAnimation =animations[randomNo]+' 2s';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.