Grow your CSS skills. Land your dream job.

[Solved] First time creating a plugin, is this proper?

  • # June 21, 2012 at 7:49 pm

    Hello internet peoples of css-tricks…

    First time creating a plugin and wondering if what im doing here is proper ( as far as event handling goes ). Do i need to do this differently or is this ok. Mainly just wondering about the keydown and keyup functions.

    (function($) {
    $.fn.codeScanner = function() {

    var $this = $(this);
    var scanID = "";

    $this.keydown(function(event) {
    scanID += "ok";
    });

    $this.keyup(function(event) {
    alert(scanID);
    });

    };
    })(jQuery);
    # June 22, 2012 at 6:24 am

    When you create a plugin you always need to return the current jQuery object for the element which allows for method chaining, also rather then using the keydown() and keyup() methods you should be using the on() method as it has event delegation built into it which allows for more dynamic event handlers in the DOM. See the below code which i updated to reflect this.

    (function($) {
    $.fn.codeScanner = function() {

    return this.each(function() {
    var scanID = '';

    this.on({
    keydown :, function(e) {
    scanID += 'ok';
    },
    keyup : function(e) {
    alert(scanID);
    }
    });
    });

    };
    })(jQuery);
    # June 22, 2012 at 12:08 pm

    @SgtLegend,

    That is super cool and thank you for that updated code. You’re correct, the .on( ) method is going to be really helpful here.

    Thanks so much. You have totally solved my problem.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".