Can I use CSS in JQuery to change a div's color slowly? Oh and one more thing, how can I add a second function to my <div>. Here is the code. I want to change the color back to the old one when mouseout happens.
<script>
function myFunction() {
$(document).ready(function () {
$("#square").css({ backgroundColor: 'blue' });
});
}
</script>
<div id="square" onmouseover="return myFunction()">Focus on me!</div>
To make it slow, give a transition and remove the document.ready as you are calling it by something not on load:
#square {transition: 1s all linear;}
Cross Browser Support
-webkit-transition: all 1s linear;
-moz-transition: all 1s linear;
-o-transition: all 1s linear;
transition: all 1s linear;
Snippet
$(document).ready(function () {
$("#square").hover(function () {
$(this).css("backgroundColor", 'blue');
}, function () {
$(this).css("backgroundColor", '');
});
});
#square {width: 100px; height: 100px; transition: 1s all linear;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="square"></div>
Note: The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.
Use .animate:
<script>
function myFunction() {
$(document).ready(function () {
$("#square").animate({
backgroundColor: 'blue'
}, 500);
});
}
</script>
In this case the transition is 500 ms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With