To create and use jQuery plugins, follow these steps:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
(function ($) {
// Plugin code here
})(jQuery);
(function ($) {
$.fn.changeColor = function (color) {
return this.each(function () {
$(this).css('background-color', color);
});
};
})(jQuery);
Inside the plugin function, use the $.fn
or jQuery.fn
object to extend jQuery's prototype with your plugin method. In the example above, $fn.changeColor
adds a method called changeColor
to the prototype of the jQuery object, allowing it to be called on any jQuery object.
To use your plugin, you can simply call it on a jQuery object. For example, if you have a <div>
with the class "myDiv", you can change its background color like this:
$('.myDiv').changeColor('red');
This will change the background color of all elements with the class "myDiv" to red.
That's it! You have created and used a jQuery plugin. You can add more functionality to your plugin by extending the $.fn
object with additional methods, just like you did with the changeColor
method.