Monday 17 June 2013

Your first jQuery plugin

Here is a quick tutorial in how to create a jQuery plugin. Below is my basic page with a call to:
A file called 'first.plugin.js' containing the plugin (in red).
A call to a method called 'changetored' within that plugin (in blue).

<!DOCTYPE html>
<html lang="en">
<head>
<title>First jquery plugin test page</title>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
<style>
.red
{
color:red;
}
</style>
</head>
<body>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
</body>
<!-- Call the plugin -->
<script src="first.plugin.js"></script>
<script>
(function()
{
/*
* changetored is a method declared in first.plugin.js
*/
$('p').changetored();
})();
</script>
</html>
Now for the plugin. Here is the file 'first.plugin.js'.

(function($)
{
$.fn.changetored = function()
{
/*
* In the context of a call like $('p').changetored();
* $(this) would become all paragraphs
*/
$(this).addClass('red');
};
})(jQuery);

No comments:

Post a Comment