How To Invert an Element’s Colors With JQuery

I have written a lot of CSS code where I wanted to invert a button, link, and many other element’s colors when the user hovered it, and all this time I’ve been using CSS’ pseudo class “:hover” when I could’ve done it a lot faster in JQuery. I did not think about this until today and in fact I wrote this script right before this post.

The JQuery functions we are going to be using are hover() and css().

Function: css(property name)

To get the element’s color, a button in this case, we’ll use css(“color”), to get its background color we will use css(“background-color”).

You can also change an element’s property by giving the property names a value. This will change a button’s font color to blue for example.

$("button").css("color":"blue");

To change more than one property at once, separate the property-value pair with comas, and put all the properties in curly brackets.

$("button").css({"color":"blue","background-color":"red"}):

Function: hover(function, function)

Hover takes to parameters, both parameters are functions.

The first function is executed when the mouse is on the element, the second function is for when the mouse moves out of it. Since we want to invert the colors when the mouse is on, and invert them back when is out, we just need to write one function.

var color;
var background_color;

function invert(){

color=$(this).css("background-color");
background_color=$(this).css("color");

$(this).css({"background-color":background_color,"color":color});
}

Am using $(this) instead of the element’s name because this will ensure that the function, which I will pass to hover(), works with any HTML tag.

Now you can use the function we just made along with hover and apply it to one or more HTML tags, in this example am inverting the colors of buttons and links.

	$("button, a").hover(invert,invert);

Here is a full script for you to try. Don’t forget to use hex or rgb color codes instead of the actual name of the color, am just using the names here to better illustrate the results.

<html>
<head>
<style type="text/css">
button{
background-color:blue;
color:white;
}
</style>
</head>
<body>
<button>Click Here!</button>
<a href="#">link</a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){

var color;
var background_color;

function invert(){

color=$(this).css("background-color");
background_color=$(this).css("color");

$(this).css({'background-color':background_color,'color':color});
}
	$("button").hover(invert,invert);

});
</script>
</body>
</html>
blog comments powered by Disqus