onmouseenter KeyFrame only works one time

71 views Asked by At

As you can see the following animation will work the first time you hover the mouse over the square but it doesnt work anymore afer the first time and thats my goal:

function js1(x){
x.style.animation="anime 1s";
}

function js2(x){
x.style.animation="anime1 1s";
}
#tria {
width: 0;
height: 0;
border-style: solid;
border-width: 50px 0 50px 200px;
border-color: transparent transparent transparent #007bff;
position:absolute;
top:200px;
}

#tria2 {
width: 0;
height: 0;
border-style: solid;
border-width: 50px 200px 50px 0;
border-color: transparent #007bff transparent transparent;
position:relative; 
float:right;
top:200px;
}

@Keyframes anime{
    from {left: 0;}
    to {left: 200px;}
}
@Keyframes anime1{
    from {left: 0;}
    to {left: -200px;}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Site 2</title>
<link href="styles.css" rel="stylesheet" type="text/css">
<script src="triascript.js"></script>
</head>

<body>

<div id="tria" onmouseenter="js1(this)"></div>
<div id="tria2" onmouseenter="js2(this)" ></div>






</body>
</html>

Other example:

https://jsfiddle.net/sergiureznicencu/4dyq1dgk/

1

There are 1 answers

0
taxicala On

Try resetting it afterwards on mouseleave:

JS:

function reset(x){
    x.style.animation = "";
}

HTML:

<div id="tria" onmouseenter="js1(this)" onmouseleave="reset(this)"></div>
<div id="tria2" onmouseenter="js2(this)" onmouseleave="reset(this)"></div>

Another way would be with a timeOut:

JS

function js1(x){
    x.style.animation="anime 1s";
    setTimeout(function() {x.style.animation = "";}, 1000);
}

function js2(x){
    x.style.animation="anime1 1s";
    setTimeout(function() {x.style.animation = "";}, 1000);
}

HTML:

<div id="tria" onmouseenter="js1(this)"></div>
<div id="tria2" onmouseenter="js2(this)" ></div>

https://jsfiddle.net/4dyq1dgk/4/