Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing color in Jquery

Tags:

jquery

css

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>
like image 377
Altay Mazlum Avatar asked Nov 20 '25 14:11

Altay Mazlum


2 Answers

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>
like image 58
Praveen Kumar Purushothaman Avatar answered Nov 22 '25 03:11

Praveen Kumar Purushothaman


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.

like image 37
KittMedia Avatar answered Nov 22 '25 04:11

KittMedia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!