jQuery capture enter key and prevent default

user961627 picture user961627 · Jan 20, 2013 · Viewed 9.4k times · Source

Referring to the answer here: How to use TinyMCE functions on text without actually selecting that text?

I've realized that

$('#TAID_ifr').contents().find('html').bind('keypress', function(e){return false;});

doesn't work for the enter key. When a user hits "enter", a newline is formed. But for all other keys, the code works as expected, i.e. nothing happens. Does enter require some special treatment? I added the code below but it didn't make a difference:

            var code = e.keyCode || e.which;
                if (code == 13) e.preventDefault();

What's wrong? I don't want a new line to be inserted when a user hits "enter", I want nothing to happen.

Edit

Does this not work because the enter key is pressed inside an iframe?

Answer

Thariama picture Thariama · Jan 21, 2013

Yes, this is possible. Tinymce uses its own event management. There is a tinymce event called onKeyDown. Using the setup configuration parameter you may use this event:

// Adds an observer to the onKeyDown event using tinyMCE.init
tinyMCE.init({
   ...
   setup : function(ed) {
      ed.onKeyDown.add(function(ed, event) {

          if (event.keyCode == 13)  {
              event.preventDefault();
              event.stopPropagation();
              return false;
          }
      });
   }
});

Be aware that several statements are used here to stop the propagation of code due to the fact that the implementation in different browsers differs.