April 4, 201313 yr Hey all, Say a piece of JS i liked and thought I'd have a play myself and see if i could make it into a jQuery plugin. I used the a boilerplate as a base. /* * Author: Ben Cleverly * Website: http://www.bencleverly.me/#plugins * Description: A plugin to create an auto generated table of contents - inspired by a post on CSS tricks - http://css-tricks.com/automatic-table-of-contents/ * License: http://opensource.org/licenses/MIT */ ;(function ($, window, document, undefined) { var pluginName = "bcToc", defaults = { contentAreaID: 'content', contentLinkClass: 'contentLink', addClassToLink: '' }; function Plugin( element, options ) { this.element = element; //create original element object this.jele = $(element); //create jquery object of element this.options = $.extend( {}, defaults, options ); //add otpions onto default for full list this._defaults = defaults; this._name = pluginName; this._links = $('#' + this._defaults.contentAreaID + ' . ' + this._defaults.contentLinkClass); this.init(); } Plugin.prototype = { init: function() { this.getItems(this.element, this.options); }, getItems: function (el, options){ var thisObj = this; $(this._links).each(function(index, element) { var newline, title = $(this).attr('title'), links = '#' + $(this).attr('name'); thisObj.setItems(title, links, thisObj.options.addClassToLink); }); }, setItems: function(title, links, classes){ newLine = '<li><a href="' + links +'" class="' + classes + '">' + title + '</a></li>'; this.jele.append(newLine); } }; $.fn[pluginName] = function ( options ) { return this.each(function () { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin( this, options )); } }); }; })( jQuery, window, document ); Wonder what improvements i could make or advice for the future. Feel free to take it and use as you want. Cheers
Create an account or sign in to comment