Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • the code doesn't imply what it does. What it does is: prevents form submittion when enter is hit on control with .editable-textbox class + control is blurred
  • of course code duplication

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

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

with jQuery.

like image 819
dragonfly Avatar asked Sep 15 '26 06:09

dragonfly


1 Answers

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.

like image 195
alex Avatar answered Sep 16 '26 19:09

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!