We've been busy with upgrading TinyMCE from 3.x to 4.2.5 and can not prevent the default ENTER action from happening.
Our goal is to submit the form when CTRL + enter is pressed, and important is that the submit should happen before the newline is added to TinyMCE. The 3.x branch allowed us to add the event to the top of the queue:
// Important: inject new eventHandler via addToTop to prevent other events
tinymce.get('tinymce_instance').onKeyDown.addToTop(function(editor, event) {
if (event.ctrlKey && event.keyCode == 13) {
$("form").submit();
return false;
}
});
Unfortunately we can not figure out how to add it to the top of the events again.
event.preventDefault() and event.stopPropagation() do not have the expected effect because the enter is already there. The weird thing is that it does work on other keys, the alphanumeric keys can be prevented. http://jsfiddle.net/zgdcg0cj/
The event can be added using the following snippet:
tinymce.get('tinymce_instance').on('keydown', function(event) {
if (event.ctrlKey && event.keyCode == 13) {
$("form").submit();
return false;
}
});
Problem: the newline is added to the TinyMCE content earlier as our event handler is called, so an unwanted enter is stored. How can I add the event to the top in the 4.x branch, or prevent the newline from happening?
event.preventDefault() works when you attach the keydown event via the setup on the init function.
tinymce.init({
selector:'textarea',
setup: function (ed) {
ed.on('keydown',function(e) {
if(e.ctrlKey && e.keyCode == 13){
alert("CTRL + ENTER PRESSED");
e.preventDefault();
}
});
}
});
This does block the carriage return from happening. JsFiddle
Edit:
Above is one way of doing it, I have found another way of achieving the result which doesn't require the init at all. Instead we create a new Editor instance and bind to our textarea given it has an id.
HTML
<form>
<!--Select by ID this time -->
<textarea id='editor_instance_1'>A different way</textarea>
</form>
JS
var ed = new tinymce.Editor('editor_instance_1', {
settings: "blah blah"
}, tinymce.EditorManager);
//attach keydown event to the editor
ed.on('keydown', function(e){
if(e.ctrlKey && e.keyCode == 13){
alert("CTRL + ENTER");
e.preventDefault();
}
});
//render the editor on screen
ed.render();
var init {
...,
setup: function (ed) {
ed.on('keydown', function (e) {
if (e.ctrlKey && 13 === e.keyCode) {
e.preventDefault();
$("form").submit();
}
});
};
tinymce.init(init);
Works for tinyMCE 4.x
Maybe I'm late, but this answer is for those who cannot(or don't want to) change init setup for tinymce. I found following method:
var frame = document.getElementById('id_of_editor_iframe');
var iframeDocument = fr.contentWindow.document;
iframeDocument.addEventListener('keydown', function(e) {
if (
[38, 40, 13].indexOf(e.keyCode) > -1 //Enter and up/down arrows or whatever you want
) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
// your code here
return false;
}
}, true);
It helped me to prevent new line in editor
Related
How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});
This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
I want to prevent the default event on key #93 (select, between alt gr and ctrl right on AZERTY keyboard).
This key open context menu like right click.
I tried :
$(document).off('keydown');
$(document).off('keyup');
$(document).off('keypress');
$(document).on('keypress', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keyup', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keydown', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
Nothing works... I have always the contextmenu.
After checking for a while, I've been headed to another question similar to this one, but with a very different matter.
In any case, since the problem is the context menu, you don't even need jQuery for such, and the solution (despite it WON'T always work in firefox because the user may set it to disable such) is this one:
document.oncontextmenu = function (e) {
e.preventDefault();
return false;
}
fiddle:
http://jsfiddle.net/0kkm1vq0/3/
Works on chrome as well, and you won't need to use the keyboard listeners.
Reference: How to disable right-click context-menu in javascript
(which is really the same as key #93).
** note that this will disable the right click too **.
EDIT:
Not sure if this is cross-browser (the UPDATED code below seems to be working for both chrome and firefox, didn't try IE and others though), but the event fired by key #97 seems to be identified as 1, while the click seems to be identified as key 3, so you can just:
(function($){
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
$(document).on('keyup', function(e) {
e.which == 93 && e.preventDefault();
});
}
else {
document.oncontextmenu = function (e) {
e.which == 1 && e.preventDefault();
}
}
})(jQuery);
http://jsfiddle.net/0kkm1vq0/10/
To disable JUST the key and not the right click.
$(function(){
$('.inviteClass').keypress(function() {
if(event.keyCode=='13') {
doPost();
}
});
Here I have one small requirement. Pressing keyboard Enter to submit the form and it is working fine in FireFox and Chrome, as well as IE 7 and 8, but it is not working in IE9 and IE 10.
Please help me.
Points to note:
You are missing a closing bracket.
Also, change the selector to window
Use .on() function
Use the .which property of event. See jQuery documentation
The keycode is an integer - remove the quotes
Add a return false; to stop the event from bubbling to the form (and possibly submitting the form twice). See Submitting a form on 'Enter' with jQuery?
Final code:
$(function() {
$(window).on('keydown', function(event) {
if(event.which == 13) {
doPost();
return false;
}
});
});
try
$('.inviteClass').keypress(function (e) {
c = e.which ? e.which : e.keyCode;
if (c == 13) {
doPost();
e.preventDefault();
return false; //<---- Add this line
}
});
you must use jQuery's event.which, also change '13' to 13 (a closing bracket was also missing):
$(function(){
$('.inviteClass').keypress(function(event) {
if(event.which == 13) {
doPost();
}
});
});
Please Try to use keydown event and also pass the event object in the function like this
$(function(){$('.inviteClass').keydown(function(event){if(event.keyCode=='13'){doPost();}});
or
$(function(){$('.inviteClass').keypress(function(event){if(event.keyCode=='13'){doPost();}});
Hope this will help you
Thanks
How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});