Altay Mazlum
Altay Mazlum

Reputation: 442

Changing color in Jquery

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>

Upvotes: 3

Views: 107

Answers (4)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

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>

Upvotes: 4

KittMedia
KittMedia

Reputation: 7466

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.

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

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

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

Upvotes: 0

Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

Combine your code with this CSS rule

#square {
   transition: 1s ease background;
}

Upvotes: 0

Related Questions