简体   繁体   中英

How to make a jquery plugin work on user defined elements

I'm making a basic jQuery plugin with which the user can change Bg-color, font-color etc.

I want the user of the plugin to be able to define the elements on which these changes become active.

I know I have to use 'this' but I don't know how to do it.

This is the code for the plugin

(function($, window, document, undefined){
//Define your own variables first

var wrapper = $('.wrapper');
var p = $('p');

//Define the default settings here
var settings = {
    textColor: 'red'
};


//Write your methods here
var methods = {
    //Call this method to initialize the plugin
    init: function(){
        console.log("Initialize the plugin");
        $('input').on('change', methods.changeColor);
        $('select').on('change', methods.changeFont);
        $('.slider').on('change', methods.changeWidth);
    },

    changeColor: function(){
        console.log("This will change the background and/or font color");

        var userBackgroundColor = $("#userBackgroundColor").val();
        var userTextColor = $("#userTextColor").val().toLocaleLowerCase();

        wrapper.css({
            backgroundColor: userBackgroundColor,
            color: userTextColor
        });
    },

    changeFont: function(){
        console.log("This will change the font");

        var userFontSize = $("option:selected").val();

        console.log(userFontSize);

        p.css({
            fontSize: userFontSize + 'em'
        })
    },

    changeWidth: function(){
        var p = $('p');
        var userWidth = $(".slider").val();

        var widthFontChange = userWidth / 20;

        if (widthFontChange == 1) {
            p.css({
                width: userWidth + '%',
                fontSize: widthFontChange + 'em'
            });
        }


        else {
            widthFontChange = userWidth / 2;
            p.css({
                width: userWidth + '%',
                fontSize: widthFontChange + 'px'
            })
        }
    }

};



//Actual plugin call
$.fn.pluginName = function(options){
    //If the user overrides defaults by setting his own options
    if(options){
        settings = $.extend(settings, options);
    }
    //Put any eventHandlers here, like this:
    this.on('change', methods.changeColor);
    this.on('change', methods.changeFont);
    this.on('change', methods.changeWidth);

    //Init the plugin with the $selector
    methods.init(this);

    //Return this for jQuery chaining
    return this;
};
}(jQuery, window, document));

And this is the file in which the user wil be able to define the object on which the plugin has to work

$(document).ready(function(){
$('body').pluginName();
});

My question is, how to I make this work the way I want it to?

If I understand your question correctly, you want to provide settings to choose the various components to listen for changes. If so...

Pass the jQuery this and the options to your init method, so it has everything it needs to hook up events to specific child elements.

I switched to using the delegated version of on as it will survive dynamic changes.

JSFiddle: http://jsfiddle.net/CgGjq/6/

The key part is

init: function ($element, options) {
            console.log("Initialize the plugin");
            $element.on('change', options.input || 'input', methods.changeColor);
            $element.on('change', options.select || 'select', methods.changeFont);
            $element.on('change', options.slider || '.slider', methods.changeWidth);
        },

Which uses properties in the options to override the selectors (or default to your plugin defaults settings if not supplied).

You can then use it with options like this:

$(document).ready(function () {
    $('body').pluginName({
        select: '#userFontSize', // Override the selectors etc
        slider: "#userWidth.slider"
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM