user961627
user961627

Reputation: 12747

jQuery capture enter key and prevent default

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?

Upvotes: 4

Views: 9629

Answers (3)

In TinyMce 4.x, use the following snippet, as documented here:

// Adds an observer to the onKeyDown event using tinyMCE.init
tinymce.init({
   ...
   setup : function(ed) {
      ed.on('KeyDown', function(event) {
          if (event.keyCode == 13)  {
              event.preventDefault();
              event.stopPropagation();
              return false;
          }
      });
   }
});

Upvotes: 0

Thariama
Thariama

Reputation: 50832

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.

Upvotes: 4

Jirilmon
Jirilmon

Reputation: 1944

Please try this code:

$('#TAID_ifr').keypress(function(event){

    if (event.keyCode == 10 || event.keyCode == 13)  {
        event.preventDefault();
    }
});

Upvotes: 0

Related Questions