How to create simple jQuery plugin?

This test plugin, is supposed to work like this: When an element is clicked, it moves down. Simple as that.

jQuery.fn.moveDown = function(howMuch){
    $(this).css("border", "1px solid black");

        $(this).css("position", "relative");
        $(this).animate({top: '+='+howMuch});

The problem is, when an element is clicked, it not only moves the clicked element but also ALL the other elements which the plugin was applied to.

What is the solution for this?



For plugin authoring try this way, much more solid:

Edit: Here is working jsFiddle example.


        YourPluginName: function(options) {
                var defaults = {
                      animation: '',//users can set/change these values
                      speed: 444,
                      etc: ''

       options = $.extend(defaults, options);

       return this.each(function() {
          var $this = $(this);              
          var button = $('a', $this);// this represents all the 'a' selectors;
                                            // inside user's plugin definition.

            $this.animate({'top':options.howMuch});//calls options howMuch value


$(function() {
     howMuch:'1000' //you can give chance users to set their options for plugins

<div id="plugin">

Here i want to suggest steps to create simple plugin with arguments.


(function($) {
    $.fn.myFirstPlugin = function( options ) {

        // Default params
        var params = $.extend({
            text     : 'Default Title',
            fontsize : 10,
        }, options);
        return $(this).text(params.text);


Here, we have added default object called params and set default values of options using extend function. Hence, If we pass blank argument then it will set default values instead otherwise it will set.


$('.cls-title').myFirstPlugin({ text : 'Argument Title' });

Read more: How to Create JQuery plugin

Original answer Here i want to suggest steps to create simple plugin with arguments


If you have Node.js installed you can use create-jquery-plugin CLI utility. Just run

npx create-jquery-plugin

Or, you can clone the jquery-plugin-boilerplate to get started.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.