A simple JS Select plugin

Source: Internet
Author: User

Now, through a select plugin, to introduce the JS plug-in construction process.

1. First on

2. Directory Construction

(1) This select plugin, I named it to Hongselect, so, first build a Hongselect folder.

(2) then build a src directory to put the source code.

(3) I want to host the source code on GitHub, so, build a readme.md file to write a description of the plugin.

(4) then build a. gitignore file to indicate that those files or folders do not need to be added to the code version management.

(5) The plugin relies on jquery, we want to download it, for JS dependency, we can use Bower to manage, and use Bower to publish our plugin.

(6) Using Bower, create a new Bower.json to configure.

(7) The final code of the packaging work, using Grunt to JS,CSS, and img file compression.

(8) Using grunt, create a new Package.json to configure.

The final directory structure is as follows (the file that is not mentioned above will be described next):

3. Source code Writing

In SRC, two more folders, a CSS folder, used to put the style file, an IMG folder, used to put the image file.

(1) JavaScript section

In SRC, create a new Hongselect.src.js file.

The source code is as follows:

(function ($) {var defaultoptions = {theme: "Default"};        Select object var hongselect = function (element, options) {var = this;        That.origin = $ (element);        That.origin.hide ();        That.options = $.extend ({}, defaultoptions, options);    That.render ();    };            Hongselect.prototype = {render:function () {var. = this;            var theme = That.options.theme; That.container = That.container | |            That.origin.after ("<div>"). Next ();            That.container.addClass (Theme + "_hongselect");            That.container.empty ();            var Infospan = that.container.append ("<span>"). Find ("span");            Infospan.addclass (Theme + "_info_span");            var dl = That.container.append ("<dl>"). Find ("DL");            Dl.addclass (Theme + "_dl"); $ (That.origin). Find ("option"). each (function (i, option) {if (i = = 0) {infospan.text (op Tion.teXT);            } dl.append ("<dd data-val=" + Option.value + ">" + option.text + "</dd>");            });            Show selected value Infospan.text ($ (that.origin). Find (' option:selected '). text ());            Hide dd items dl.hide ();            var dd = dl.find ("dd");            Dd.addclass (Theme + "_dd");            Dd.hover (function () {$ (this). addclass (Theme + "_dd_hover");            }, Function () {$ (this). Removeclass (Theme + "_dd_hover");            });                Show and Hide Infospan.click (function (e) {e.preventdefault ();                E.stoppropagation ();            Dl.show ();            });                    Dd.each (function () {$ (this). Click (function () {Infospan.text ($ (this). text ());                    $ (That.origin). Val ($ (this). attr ("Data-val"));                $ (That.origin). Trigger ("change");    });        });            Click Blank Hide $ (document). Click (function () {dl.hide ();        });            }, Setselectval:function (value) {this.origin.val (value);        This.render ();        }, Refresh:function () {this.render ();    }    };        $.fn.hongselect = function (option) {var args = array.apply (null, arguments);        Args.shift (); This.each (function () {var $this = $ (this), data = $this. Data (' Hongselect '), opt            ions = typeof option = = ' object ' && option;            if (!data) {$this. Data (' Hongselect ', (data = new Hongselect (this, options))); } if (typeof option = = ' string ' && typeof data[option] = = ' function ') {Data[option].app            Ly (data, args);        }        });    return this; };}) (JQuery);

Code Explanation:

1) Global isolation function

(function ($) {    //...}) (JQuery);

What is the function of using such an immediate function? This is done to isolate our plug-in code from the global Code, all in the function scope, thus preventing global variable pollution.

2) extending jquery

$.fn.hongselect = function (option) {        var args = array.apply (null, arguments);        Args.shift ();        This.each (function () {            var $this = $ (this),                data = $this. Data (' Hongselect '),                options = typeof option = = ' Obje CT ' && option;            if (!data) {                $this. Data (' Hongselect ', (data = new Hongselect (this, options)));            }            if (typeof option = = ' string ' && typeof data[option] = = ' function ') {                data[option].apply (data, args);            }        });        return this;    };

This is a jquery extension of a hongselect method. $.fn What is this? This FN is both JavaScript prototype,jquery just use FN instead of prototype, so you can see why $.fn.hongselect can use $ (' selector '). Hongselect () Such a way to use it.

The other code is relatively simple, not a detailed explanation.

(2) The next step is to write CSS.

Create a new Hongselect.css file in the CSS.

. default_hongselect {    width:150px;    Position:absolute;}. Default_info_span {    cursor:pointer;    text-indent:10px;    Color: #666;    Display:block;    padding-right:20px;    height:30px;    line-height:25px;    Background:url (.. /img/arrow.png) No-repeat Right center;    position:relative;    border:1px solid #ccc;    text-overflow:ellipsis;    Overflow:hidden;}. DEFAULT_DL {    border-bottom:1px solid #ccc;    margin:1px 0 0;}. DEFAULT_DD {    cursor:pointer;    height:30px;    line-height:25px;    Color: #666;    White-space:normal;    padding:0 10px;    Background: #f1f1f1;    margin:0;    border-left:1px solid #ccc;    border-top:1px solid #ccc;    border-right:1px solid #ccc;    text-overflow:ellipsis;    Overflow:hidden;}. default_dd_hover {    background: #fff;}  

  (3) Put the picture in the IMG file

OK, the code is written.

4. Testing

Configure Bower.json

{  "name": "Hongselect",  "version": "0.0.1",  "homepage": "Https://github.com/liuhongqiang/hongselect",  "Authors": [    "Liuhongqiang <[email protected]>"  ],  "description": "A Simple Web Select.",  "Main": "Src/hongselect.src.js",  "keywords": [    "select"  ],  "license": "MIT",  "Ignore": [    "Node_modules",    "Bower_components"  ],  "devdependencies": {    "jquery": "2.1.4"  }}

Use commands on the command line to download jquery, see Bower official website for specific instructions.

Bower Install

Once the command is invoked, a bower_components folder is created in the current directory and the JS we rely on is downloaded to that directory.

Then we can refer to it for testing, we build a doc/example to put our test files.


 

5. Packaging

Well, after the project is tested, we can pack the plugin.

We use grunt to package it, the grunt configuration is as follows, the specific use method see official website.

1) Package.json

{    "name": "Hongselect",    "version": "0.0.1",    "description": "A Simple Web Select.", "    dependencies": {" Grunt ":" ^0.4.5 "," grunt-contrib-uglify ":" ~0.2.2 "," Grunt-contrib-clean ":" ~0.6.0 "," Grunt-contrib-cssmin ":" ~0.10.0 "," Grunt-contrib-imagemin ":" ~0.7.0 "}}

2) Gruntfile.js

Module.exports = function (grunt) {Grunt.initconfig ({Pkg:grunt.file.readJSON ("Package.json"), clean: {                Build: {src: ["dist/**"]}}, Uglify: {build: {            SRC: "Src/hongselect.src.js", dest: "Dist/hongselect.min.js"}, Cssmin: {            Build: {src: "src/css/hongselect.src.css", dest: "Dist/css/hongselect.min.css"  }}, Imagemin: {build: {src: "src/img/arrow.png", dest:    "Dist/img/arrow.png"}});    Register plugin grunt.loadnpmtasks ("Grunt-contrib-clean");    Grunt.loadnpmtasks ("grunt-contrib-uglify");    Grunt.loadnpmtasks ("Grunt-contrib-cssmin");    Grunt.loadnpmtasks ("Grunt-contrib-imagemin");    The list of tasks that are performed by default. Grunt.registertask ("Default", ["clean", "uglify", "Cssmin", "imagemin"]);

Invoking grunt with the command line will put the compressed JS, CSS, img into the dist directory.

Grunt

6. Release

Published by Bower Command

Bower Register <my-package-name> <git-endpoint>

  

After publishing, you can find the following on Bower.io:

7. Hosting

Host your code on GitHub via Git.

git addgit commitgit push

  

Address: Https://github.com/liuhongqiang/hongselect

A simple JS Select plugin

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.