Changing color in JQuery

Can I use CSS in JQuery to change colors slowly div

? Oh, and one more thing, how to add a second function to mine <div>

. Here is the code. I want to change the color to old when it happens mouseout

.

<script>
    function myFunction() {
        $(document).ready(function () {
            $("#square").css({ backgroundColor: 'blue' });

        });

    }
</script>

<div id="square" onmouseover="return myFunction()">Focus on me!</div>

      

+3


source to share


4 answers


To make it slow, give transition

and remove document.ready

, as you are calling it something not to 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;

      



Excerpt

$(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>
      

Run codeHide result


+4


source


Note. The jQuery UI project extends the .animate () method to allow some non-numeric styles such as animated colors. The project also includes mechanisms for defining animations via 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 500

ms.

+1


source


You can use .animate()

to set the delayed css effect:

$("#square").animate({backgroundColor: 'blue'}, 500});

      

0


source


Combine your code with this CSS rule

#square {
   transition: 1s ease background;
}

      

0


source







All Articles