A jump-start for jQuery plugins development

Overview

jQuery Boilerplate Build Status Bower Version

A jump-start for jQuery plugins development

So, you've tried your hand at writing jQuery plugins and you're comfortable putting together something that probably works. Awesome! Thing is, you think there might be better ways you could be writing them - you've seen them done a number of different ways in the wild, but aren't really sure what the differences between these patterns are or how to get started with them.

This project won't seek to provide a perfect solution to every possible pattern, but will attempt to cover a simple template for beginners and above. By using a basic defaults object, simple constructor for assigning the element to work with and extending options with defaults and a lightweight wrapper around the constructor to avoid issues with multiple instantiations.

Usage

  1. Include jQuery:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  2. Include plugin's code:

    <script src="dist/jquery.boilerplate.min.js"></script>
  3. Call the plugin:

    $("#element").defaultPluginName({
    	propertyName: "a custom value"
    });

Structure

The basic structure of the project is given in the following way:

├── demo/
│   └── index.html
├── dist/
│   ├── jquery.boilerplate.js
│   └── jquery.boilerplate.min.js
├── src/
│   ├── jquery.boilerplate.coffee
│   └── jquery.boilerplate.js
├── .editorconfig
├── .gitignore
├── .jshintrc
├── .travis.yml
├── Gruntfile.js
└── package.json

demo/

Contains a simple HTML file to demonstrate your plugin.

dist/

This is where the generated files are stored once Grunt runs.

src/

Contains the files responsible for your plugin, you can choose between JavaScript or CoffeeScript.

.editorconfig

This file is for unifying the coding style for different editors and IDEs.

Check editorconfig.org if you haven't heard about this project yet.

.gitignore

List of files that we don't want Git to track.

Check this Git Ignoring Files Guide for more details.

.jshintrc

List of rules used by JSHint to detect errors and potential problems in JavaScript.

Check jshint.com if you haven't heard about this project yet.

.travis.yml

Definitions for continous integration using Travis.

Check travis-ci.org if you haven't heard about this project yet.

Gruntfile.js

Contains all automated tasks using Grunt.

Check gruntjs.com if you haven't heard about this project yet.

package.json

Specify all dependencies loaded via Node.JS.

Check NPM for more details.

Guides

How did we get here?

Have you got in this repo and still not sure about using this boilerplate?

Well, extending jQuery with plugins and methods is very powerful and can save you and your peers a lot of development time by abstracting your most clever functions into plugins.

This awesome guide, adapted from jQuery Plugins/Authoring, will outline the basics, best practices, and common pitfalls to watch out for as you begin writing your plugin.

How to publish plugins?

Also, check our guide on How to publish a plugin in jQuery Plugin Registry!

Note: The jQuery Plugin Registry is in read-only mode. New plugin releases will not be processed. jQuery recommends moving to npm, using "jquery-plugin" as the keyword in your package.json. See how to publish into npm registry.

Team

jQuery Boilerplate was made with love by these guys and a bunch of awesome contributors.

Zeno Rocha | Addy Osmani | Helder Santana --- | --- | --- | --- | --- | --- | --- Zeno Rocha | Addy Osmani | Helder Santana

Contributing

Check CONTRIBUTING.md for more information.

History

Check Releases for detailed changelog.

License

MIT License © Zeno Rocha

Comments
  • Add more documentation/examples

    Add more documentation/examples

    1. For example: document how to pass method calls to plugin (how to implement API). Solution is
    $('#selector').tooltip({...}); //init
    $('#selector').tooltip('show'); //show
    $('#selector').tooltip('hide'); //hide
    

    For solution see http://docs.jquery.com/Plugins/Authoring#Data 2. Document how/when use custom events

    etc

    good source http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/ (github)

    opened by stereobooster 11
  • Allow access to public prototype methods

    Allow access to public prototype methods

    I saw that you wanted to add this functionality based on @dbashyal's issue, so I figured I'd get my fork up to date and submit a pull request.

    Another really useful feature I've since added (which I think is a vital part of this update) is the ability to remove instances of the plugin via the 'destroy' method, e.g. I use $.stellar('destroy') in my Stellar.js plugin. It calls my internal 'destroy' method, so I can do some necessary clean-up, then removes the instance from the data.

    Let me know if there are any changes you'd like me to make :)

    opened by markdalgleish 9
  • Fix coding style, devDependencies, dependencies and ignore common files

    Fix coding style, devDependencies, dependencies and ignore common files

    • FIX
      • Coding style: fix style according to the jQuery style guide.
      • Remove unnecessary "grunt-cli" from devDependencies in the package.json file. grunt-cli must be installed globally via [sudo] npm install -g grunt-cli as the getting-started guide shows.
      • Add jQuery as dependency of npm and bower package.
      • Ignore npm-debug.log, bower_components and node_modules.
        • bower_components/ will store the jQuery package. It must be ignored in .gitignore, bower.json, and .npmignore because:
          1. .gitignore: It must not be uploaded on the git repository. Dependecies must be installed locally via Bower;
          2. .npmignore: It is already a node dependency, so it will be installed with npm;
          3. bower.json: It will be installed automatically by bower in the bower_components/ folder later and this folder won't be necessarily in the plugin folder.
        • node_module must be ignored by git and Bower because of grunt. Node modules must be stored locally and then installed via npm.
    opened by ctrlmaniac 8
  • Sugestão de reformulação

    Sugestão de reformulação

    Realizei algumas alterações que achei conveniente com o proposito de aumentar o desempenho e adicionar algumas coisas, como uma função para alteração de setup e um objeto de informações.

    https://github.com/DiegoLopesLima/jquery-boilerplate/blob/master/jquery.boilerplate.js

    Teste realizado no jsPerf comparando a versão atual: http://jsperf.com/reformula-o-jquery-boilerplate

    Exemplo de uso no jsFiddle: http://jsfiddle.net/wK2ts/

    opened by DiegoLopesLima 8
  • How to instantiate the plugin?

    How to instantiate the plugin?

    Sorry, my friends, but I will write my question in portuguese. This is the first time i will send a issue, so if has something wrong with my question, please tell me.

    No site em português do jqueryboilerplate (br.jqueryboilerplate.com) existe a informação de que o aplicativo "Não adere às sugestões feitas pela documentação do jQuery em relação ao Plugins/Authoring e fazendo isso provê melhor performance e uso de memória por não criar múltiplas instâncias de si mesmo".

    Eu criei um plugin para modal que é acionado a partir de um botão. Fiz o plugin baseado nesta documentação Plugins/Authoring e tive este problema de múltiplas instâncias. Encontrei o jqueryboilerplate(v3-0) e tentei remodelar meu plugin baseado nele, mas estou com uma dúvida básica: como devo fazer a chamada ao plugin?

    $(function(){ $('button.modal').click(function() { ??? }); });

    opened by mila85 6
  • Move parens inside function invocation

    Move parens inside function invocation

    JSLint and JSHint both prefer

    (function($) {
      ...
    }(jQuery));
    

    to

    
    (function($) {
      ...
    })(jQuery);
    

    I'm not entirely sure of the reasoning, but I prefer my boilerplate pass my JSHint checks. (And if you know of a good reason not to do this, I'll gladly change my JSHint checks :) )

    master discussion 
    opened by jamesarosen 6
  • how to pass element to event callback function

    how to pass element to event callback function

    Hey guys, thanks for the amazing work!

    My code is exactly the same as the default plugin boilerplate I just replace the init function

    init: function() {
        $(this.element).find('button').on('click',function(e){
            e.preventDefault();
            console.log(this.element);
            console.log(this.options);
        }); 
    }
    

    of course the logs return undefined do u have any recommendation / good practice to access element and options in the scope of the callback function Thanks for your help

    opened by jeremycastelli 5
  • Assign methods to the prototype object, instead of overwriting the prototype with a new object.

    Assign methods to the prototype object, instead of overwriting the prototype with a new object.

    Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!

    See this shamelessly plugged example from airbnb javascript styleguide.

    Now the boilerplate has this structure, which overwrites inheritance :/

    
    Jedi.prototype = {
      fight: function fight() {
        console.log('fighting');
      },
    
      block: function block() {
        console.log('blocking');
      }
    };
    

    A suggestion would be to use this practice instead,

    Jedi.prototype.fight = function fight() {
      console.log('fighting');
    };
    
    Jedi.prototype.block = function block() {
      console.log('blocking');
    };
    
    opened by julienbechade 5
  • unit testing boilerplate?

    unit testing boilerplate?

    any chance this repo would be open to adding a unit testing boilerplate to give the boilerplate users a starting point (or recipes) for unit testing their plugins created with the boilerplate?

    opened by radiovisual 4
  • Remove closure wrapper from CoffeeScript version

    Remove closure wrapper from CoffeeScript version

    The first comment in the CoffeeScript version says:

    Note that when compiling with coffeescript, the plugin is wrapped in another anonymous function.
    

    So why add another one then?

    To localise window and document and $, you can just declare them at the top. This gets exactly the same job done – localising the variables for performance/minification – in a way that is cleaner and more straightforward.

    opened by callumlocke 4
  • Accessing plugin method

    Accessing plugin method

    Hi, Thanks for the code. Can you please help me with one problem i am having. Please see: https://github.com/dbashyal/Social-Share-Bar/blob/master/cfshare.js I need to call reposition() method on window scroll, How can i do that? I tried few options but i keep getting not a function error. Thanks.

    opened by dbashyal 4
  • How to Update Default Settings

    How to Update Default Settings

    The boilerplate uses a defaults object, but what does the code look like to update a setting of the plugin globally?

    For example, if my plugin has a default setting message: 'Hello, world!' how can I update that default setting, so that anytime the plugin is called it would already be changed to message: 'New message.'

    I have tried something like this

    myPlugin.defaults = {
        message: 'New message.'
    };
    
    opened by jstnbr 0
  • Error on

    Error on "karma:travis" task on MacOS

    Running npm test on MacOS 10.12.2 I receive the following:

    Running "karma:travis" (karma) task
    Verifying property karma.travis exists in config...OK
    File: [no files]
    Options: background=false, client={}
    30 08 2017 20:40:46.801:INFO [karma]: Karma v0.13.22 server started at http://localhost:9876/
    30 08 2017 20:40:46.816:INFO [launcher]: Starting browser PhantomJS
    30 08 2017 20:40:46.940:ERROR [launcher]: Cannot start PhantomJS
    
    30 08 2017 20:40:46.952:INFO [launcher]: Trying to start PhantomJS again (1/2).
    30 08 2017 20:40:47.063:ERROR [launcher]: Cannot start PhantomJS
    
    30 08 2017 20:40:47.073:INFO [launcher]: Trying to start PhantomJS again (2/2).
    30 08 2017 20:40:47.200:ERROR [launcher]: Cannot start PhantomJS
    
    30 08 2017 20:40:47.220:ERROR [launcher]: PhantomJS failed 2 times (cannot start). Giving up.
    Warning: Task "karma:travis" failed. Use --force to continue.
    
    Aborted due to warnings.
    
    npm ERR! Darwin 16.3.0
    npm ERR! argv "/usr/local/Cellar/node/7.6.0/bin/node" "/usr/local/bin/npm" "run" "test"
    npm ERR! node v7.6.0
    npm ERR! npm  v4.1.2
    npm ERR! code ELIFECYCLE
    npm ERR! [email protected] test: `npm run jscs && grunt travis --verbose`
    npm ERR! Exit status 3
    npm ERR!
    npm ERR! Failed at the [email protected] test script 'npm run jscs && grunt travis --verbose'.
    npm ERR! Make sure you have the latest version of node.js and npm installed.
    npm ERR! If you do, this is most likely a problem with the jquery-boilerplate package,
    npm ERR! not with npm itself.
    npm ERR! Tell the author that this fails on your system:
    npm ERR!     npm run jscs && grunt travis --verbose
    npm ERR! You can get information on how to open an issue for this project with:
    npm ERR!     npm bugs jquery-boilerplate
    npm ERR! Or if that isn't available, you can get their info via:
    npm ERR!     npm owner ls jquery-boilerplate
    npm ERR! There is likely additional logging output above.
    
    npm ERR! Please include the following file with any support request:
    npm ERR!     /Users/mgargano/delete/jquery-boilerplate/npm-debug.log
    
    opened by matgargano 0
  • jquery-boilerplate is giving some error

    jquery-boilerplate is giving some error

    Hi,

    Here is the demo

    When I click submit button, it's saying this.submitForm is not a function No idea, any help would be greatly appreciated.

    Cheers Prashant

    opened by prashant-saxena 0
  • Fix `.editorconfig` settings for rc, JSON and YAML files

    Fix `.editorconfig` settings for rc, JSON and YAML files

    The EditorConfig documentation (§ file-format-details) states:

    {s1,s2,s3}: Matches any of the strings given (separated by commas) (Available since EditorConfig Core 0.11.0)

    The current setup does not work neither when editing nor when creating files (rc files, *.json, *.yml). It should be changed to:

     # Json, YAML and Configuration files
    -[.*rc,*.{json,yml}]
    +[{.*rc,*.{json,yml}}]
     indent_style = space
     indent_size = 2
    

    With the fixed setup, the EditorConfig settings apply properly for rc files, *.json, *.yml. Tested with the Atom plug-in and by linting the whole project with the echint package.

    Note: It does not work with the Sublime Text plug-in neither with the old nor with the updated setup.

    opened by raduserbanescu 0
  • Should the plugin template still use undefined passed as a parameter

    Should the plugin template still use undefined passed as a parameter

    This file provides an example of undefined being passed as an argument to a function:

    ;( function( $, window, document, undefined ) {
        //omitted for brevity
    })($, window, document);
    

    The idea here seems to be to make sure undefined is really undefined by not passing it into the actual call. However, I believe this is no longer necessary in ES5+ compliant browsers.

    These days, it's actually safer not to do it as it introduces a way for a developer to introduce a local variable named undefined by accidentally calling the function with too many arguments. MDN seems to advise against that and personally, I agree.

    Later in the same script, there's a comment saying:

        // undefined is used here as the undefined global variable in ECMAScript 3 is
        // mutable (ie. it can be changed by someone else). undefined isn't really being
        // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
        // can no longer be modified.
    

    I understand that the fact the template still uses this practice is a conscious decision based on the team's belief in continuing to do it to cater for pre-ES5 browsers. However, I think it should also be mentioned very explicitly that this actually introduces a risk in modern browsers and should only be done if one actually wants to support ES3 browsers.

    What do you think?

    opened by toniedzwiedz 1
  • Beautify and ESLint supports

    Beautify and ESLint supports

    opened by lelinhtinh 0
Releases(v4.1.0)
Owner
jQuery Boilerplate
jQuery Boilerplate
A lightweight jQuery plugin for collapsing and expanding long blocks of text with "Read more" and "Close" links.

Readmore.js V3 alpha I am deprecating the 2.x version of Readmore.js. A new version is coming soon! Check it out and help me test it! Readmore.js A sm

Jed Foster 1.5k Nov 30, 2022
An easy to use, yet advanced and fully customizable javascript/jQuery paginator plugin

anyPaginator An easy to use, yet advanced and fully customizable Javascript/jQuery paginator plugin. anyPaginator is a spinoff of the anyList project

Arne Morken 2 Feb 17, 2022
A variety of jQuery plugin patterns for jump starting your plugin development

jQuery Plugin Patterns So, you've tried out jQuery Boilerplate or written a few of your own plugins before. They work to a degree and are readable, bu

jQuery Boilerplate 1.6k Dec 31, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
ForgJs is a javascript lightweight object validator. Go check the Quick start section and start coding with love

Hey every one im really happy that this repo reached this many stars ?? ,but this repo needs your contibution I started to better document the code th

Hamdaoui Oussama 1.7k Dec 21, 2022
An example repository on how to start building graph applications on streaming data. Just clone and start building 💻 💪

Example Streaming App ?? ?? This repository serves as a point of reference when developing a streaming application with Memgraph and a message broker

Memgraph 40 Dec 20, 2022
This plugin for Obsidian enables you to quickly jump to internal and external links

Obsidian Quick Jump Plugin This plugin for Obsidian enables you to quickly jump to internal and external links. This plugin is inspired by Jump to lin

Tadashi Aikawa 9 Sep 24, 2022
jump to local IDE source code while click the element of browser automatically.

?? Introduction A vite plugin which provides the ability that to jump to the local IDE when you click the element of browser automatically. It support

webfansplz 413 Dec 30, 2022
Use javascript and css to build a StreetFighter Ryu,walk,jump,basic punch kick,launch fireball and dragon punch.

SFRyu Use javascript and css to build a StreetFighter Ryu,walk,jump,basic punch kick,launch fireball and dragon punch. 因為小時候就很喜歡玩快打旋風,於是用Javascript,CS

null 21 Sep 1, 2022
Jump to github urls (browser addon)

Currently a Firefox addon. Find GitHub locations quickly using your browser's history. Usage Use your mouse or keyboard. Use the filter to search for

madprops 4 Nov 28, 2022
🦋 Jump to local IDE source code while click the element of browser automatically

?? Why When developing a React app, you have a lot of components in your app. Sometimes you may forget where the code is located that you want to edit

Frozen FIsh 95 Aug 17, 2022
HackMIT 2022. 2nd Place in Blockchain for Society sponsored by Jump Crypto. A revolutionary web application that leverages machine learning and blockchain technology to improve the crowdsourcing experience!

?? Wikisafe ?? Wikisafe is a revolutionary new crowdsourcing web application that innovates the process of crowdsourcing information. This application

Benson Liu 5 Dec 8, 2022
Shield is a development framework for circom developers. The core reason is to provide libraries, plugins, and testing tools to ensure code quality and security.

SHIELD Shield is a development framework for circom developers but we plan it to other languages such as CAIRO, SNARKYJS etc. The core reason is to pr

Xord 41 Dec 22, 2022
🏝 Opinionated Web Components Starter template to help kick-start development of a cross-framework component library.

Web Component Library Starter Kit "Why create components for a specific framework when it can be written to be understood by all — including browsers?

Open Web Labs 14 Dec 24, 2022
🏝 Opinionated Web Components Starter template to help kick-start development of a cross-framework component library.

Web Component Library Starter Kit "Why create components for a specific framework when it can be written to be understood by all — including browsers?

Open Web Labs 5 May 1, 2022
jQuery Timer: Start/Stop/Resume/Remove pretty timer inside any HTML element.

jQuery Timer plugin Lightweight, well tested jQuery pretty timer plugin Start, Pause, Resume and Remove a timer inside any HTML element. Get notified

Walmik Deshpande 291 Nov 4, 2022
Dynamic-web-development - Dynamic web development used CSS and HTML

Dynamic-web-development ASSISNMENT I just used CSS and HTML to make a mobile int

null 1 Feb 8, 2022
Terra development environment for better smart contract development experience.

Terrain Terrain – Terra development environment for better smart contract development experience Terrain will help you: scaffold your dapp project eas

Terra 37 Dec 19, 2022