3

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>
Altay Mazlum
  • 442
  • 5
  • 15

4 Answers4

4

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>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

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.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
KittMedia
  • 7,368
  • 13
  • 34
  • 38
0

You can use .animate() to set the css effect with delay:

$("#square").animate({backgroundColor: 'blue'}, 500});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

Combine your code with this CSS rule

#square {
   transition: 1s ease background;
}
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378