0

I'm trying to write a simple plugin, enterkeypress, which extends the keypress event, but only fires when the key pressed is the enter key:

(function ($) {
  $.fn.enterkeypress = function (fn) {
    return this.keypress(function(event){
      if(event.which == '13'){
        event.preventDefault();
        fn();
        }
    });
  };
})(jQuery);

when testing this out, it correctly fires the event but the 'this' keyword references the window, not the element.

$(":text").enterkeypress(function(){console.log(this)});

that code will output Window in the console... I'd rather it output the input control.

What am I doing wrong here?

2 Answers 2

1

Use call or apply on the callback to alter the this reference:

(function ($) {
  $.fn.enterkeypress = function (fn) {
    return this.keypress(function(event){
      if(event.which == '13'){
        event.preventDefault();
        fn.apply(this);
        }
    });
  };
})(jQuery);
Sign up to request clarification or add additional context in comments.

Comments

0

The fn callback parameter being passed is still called using the global scope which is window. You should use either call or apply to execute fn using the jquery objects context.

Try this:

 (function ($) {
      $.fn.enterkeypress = function (fn) {
        return this.keypress(function(event){
          if(event.which == '13'){
            event.preventDefault();
           //#####NOTICE THE CHANGE HERE###.
            fn.call(this);
            }
        });
      };
    })(jQuery);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.