Recently asked from me that how to create a simple function, as mouse move background color of defined area will automatically change and when mouse leave the specific area previous color will come back. So, I have created a simple hover effect jQuery plugin. By writing a jQuery plugin, you can save the developer time and can easily use in your web site application.
In this article, we will learn how to create a simple hover effect jQuery plugin.
Step 1: Firstly, I have created plugin JavaScript file with named AamirHasan.HoverEffect.js and add the Microsoft CDN jQuery library and AamirHasan.HoverEffect.js plugin reference inside head section of aspx page as shown below.
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"
type="text/javascript"></script>
<script src="AamirHasan.hovereffect.js" type="text/javascript"></script>
Step 2: In this js file, I have added new function to jQuery.fn Object. For Default settings I have used $.extend. $.extend to combine more than one object into first object. By using Namespacing, you can avoid with conflict with other plugin with same name.
Step3: Copy and paste the following code inside the AamirHasan.HoverEffect.js file.
(function($){
jQuery.fn.extend({
HoverEffect:function(options){
var defaults ={
backgroundColor:"#fff"
};
var options = $.extend(defaults, options);
returnthis.each(function(){
jQuery(this).hover(
function(){
$(this).css("background-color", options.backgroundColor)},
function(){
$(this).css("background-color","")}
);
});
}
});
})(jQuery);
Step 4: Save and close plugin file.
In the above jQuery plugin, I have added backgroundColor parameter. Now, you can use this HoverEffect plugin.
Let us see the code.
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<style>
#msg
{
background-color: #eaeaea;
border: 1pxsolid#999;
width: 400px;
height: 200px;
padding: 20px;
}
</style>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"
type="text/javascript"></script>
<script src="AamirHasan.hovereffect.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#msg').HoverEffect();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="msg">
.NET Articles<br/>
Author:Aamir Hasan
</div>
</form>
</body>
</html>
By adding jQuery library, will come to know that you are extending the methods. We can call the Hovereffect on any contents of the page.
Example 1
<script type="text/javascript">
$(function(){
$('#msg').HoverEffect();
});
</script>
Example 2
<script type="text/javascript">
$(function(){
$('p').HoverEffect({backgroundColor:"red"});
});
</script>
Example 3
<script type="text/javascript">
$(function(){
$('#example3 tr').HoverEffect({backgroundColor:"#FF0"});
});
</script>
Output

I have tested this example on following browsers:
-
Internet explorer 9 & 10
-
Firefox 7.0
-
Chrome 12.0
-
Opera 12
- Safari
Download
jQuery-Plugin-HoverEffect.zip (1.42 kb)
See live demo