dragonfly
dragonfly

Reputation: 17773

How to encapsulate JavaScript code as jQuery plugin or other solution

I have a following piece of code on a few pages, and I'll need it on even more:

        $('.editable-textbox').live('keypress', function(e) {
            if (e.keyCode == 13) {
                $(this).blur();
                return false;
            }
            return true;
        }).live('keyup', function(e) {
            if (e.keyCode == 13) {
                $(this).blur();
                return false;
            }
            return true;
        });

There're a few drawbacks of it:

I just wonder: is there a way to refactor it to have something like this:

$('.editable-textbox').supressFormSubmitOnEnter();

with jQuery.

Upvotes: 3

Views: 562

Answers (2)

alex
alex

Reputation: 490333

Yes.

$.fn.supressFormSubmitOnEnter = function() {
    return this.live('keypress', function(e) {
            if (e.keyCode == 13) {
                $(this).blur();
                return false;
            }
            return true;
        }).live('keyup', function(e) {
            if (e.keyCode == 13) {
                $(this).blur();
                return false;
            }
            return true;
        });
};

You should give the Plugin Authoring Guide a read.

Also, it could be written much terser...

$.fn.supressFormSubmitOnEnter = function() {
    return $(document).on('keypress keyup', this, function(e) {
            if (e.keyCode == 13) {
                $(this).blur();
                e.preventDefault();
            }
        });
};

jsFiddle.

Upvotes: 7

davids
davids

Reputation: 6371

You've got a great resource in the jQuery Docs

Upvotes: -1

Related Questions