jQuery provides a property ‘fn’ in the core jQuery or $ class(!#$%). You can attach your own function to the “fn” property.
Let’s say you have a header with id as ‘info’ and you want to display the current date by writing
$(“#info”).date()
You can attach a date function in the core jQuery API like below:
$.fn.date = function(){
$(this).text(new Date()+””);
}
Pretty simple!!! Isn’t? Let’s try another one.
Say, you want to change the text color of an element by having your own function changeColor.
$.fn.changeColor = function(color){
$(this).css(“color”,color);
}
Huh!!!Even better.
Usually plugins are created in a JS file jquery-xxx.js. But to keep things simple, I have used the code inline. The complete code is given below.
<!DOCTYPE html>
<html>
<head>
<script src=”jquery-1.6.1.js”></script>
<script>
$.fn.changeColor = function(color){
$(this).css(“color”,color);
}
$.fn.date = function(){
$(this).text(new Date()+””);
}
$().ready(function(){
$(“#info”).date();
$(“#welcome”).changeColor(“red”);
});
</script>
</head>
<body>
<h2 id=”welcome”>jQuery Plugin</h2>
<h5 id=”info”></h5>
</body>
</html>
We will discuss few more points of plugin in the subsequent posts. Have fun!!!