Reputation: 31
What i'm after is when I hover over an element with the ID #work, I want the background to animate into a different color. Hence this code:
$("#work").on('mouseenter', function() {
$(".wrapper").animate( {"background-color": '#EF6C00'});
})
And when the mouse doesn't hover over the element and leaves, i want it to go back to it's original color. Hence this code:
$("#work").on('mouseleave', function() {
$(".wrapper").animate( {"background-color": '#395eb0'});
})
Now to my problem. When i'm trying to tell jQuery that when I click on the element, It should keep the color it's animating to. Which simply doesn't work at all. Here's the full code:
$("#work").on('mouseenter', function() {
$(".wrapper").animate( {"background-color": '#EF6C00'});
})
$("#work").on('mouseleave', function() {
$(".wrapper").animate( {"background-color": '#395eb0'});
})
$("#work").on('click', function() {
$(".wrapper").css("background-color", '#EF6C00');
});
Upvotes: 2
Views: 233
Reputation: 43479
First of all you need some plugin that has color animation. Try jQuery UI or this answer
Now what happens with your code:
So you need to stop animation first.
$(document).ready(function() {
$("#work").on('mouseenter', function() {
$(".wrapper").stop().animate({
"background-color": '#ef6C00'
}, 2000);
})
$("#work").on('mouseleave', function() {
$(".wrapper").stop().animate({
"background-color": '#395eb0'
}, 2000);
})
$("#work").on('click', function() {
$(".wrapper").stop().css("background-color", '#ef6C00');
});
});
.wrapper {
width: 150px;
height: 150px;
border: 1px solid #ddd;
background-color: #ef6C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="wrapper" id="work"></div>
Upvotes: 1