简体   繁体   中英

How can I adjust this javascript code so an animation is activated whenever the mouse hovers over the element?

So I used this code from Justin Aguilar's CSS3 Animation Cheat Sheet to activate an animation on a button when I hover over it:

<div id="object" class="pulse">
<script>
$('#animatedElement').hover(function() {
    $(this).addClass("pulse");
});
</script>

The problem is that the animation just continues even when I am no longer hovering over the button. What can I do to make a button animate every time a user hovers over it, but stop when they move the mouse away? Whenever I tried to tweak it with anything involving .stop, it just keeps the animation from playing at all.

I am new to coding and this has been a huge pain today, so any help would be very much appreciated! Thanks!

You don't need JavaScript for that at all. Use CSS selectors. #animatedElement:hover in your case.

Here you go with one more solution

 $('#animatedElement').hover(function() { $(this).addClass("pulse"); }).mouseleave(function(){ $(this).removeClass("pulse"); }); 
 .pulse { background: #000; color: #fff; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="animatedElement">Hover Me!!!</div> 

Hope this will help you.

the hover() method accepts two callbacks: one for when the mouse enters the html element, and one for when it leaves. Therefore, you could simply add another callback to your function to remove the "pulse" class.

$('#animatedElement').hover(function() {
  $(this).addClass("pulse");
},
function(){
  $(this).removeClass("pulse");
});

Alternatively, you could just go with Alex's excellent answer.

You can use CSS to make an animation, for example, in this code:

.pulse {
    background: GREEN;
    border-radius: 6px
    transition-property: background, border-radius;
    transition-duration: 1s;
    transition-timing-function: linear;
}
.pulse:hover {
    background: BLACK;
    border-radius: 50%;
}

You have set in css the start properties for the element, and transition declaration, in this example i'm going to do a transition in the background and the radius properties when hover on a element with pulse class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM