I have a button and the following javascript routine.
$("button").keydown( function(key) {
switch(key.keyCode) {
case 32: //space
return false;
}
} );
as I understood it, the return false; would stop the keypress from being processed. So $("button").click(); would not be called. For other keyCodes, this works as expected. For example, if I intercept40, which is the down button, the page is not scrolling.
I noticed this behavior in Firefox.
Why does the return false; does not stop the button click event on space? What does the javascript spec say about this?
Hope this answers your question:
<input type="button" value="Press" onkeydown="doOtherStuff(); return false;">
return false; successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML. This behaviour is not formally specified anywhere as far as I know.
If you instead set an event via an event handler property on the DOM element (e.g. button.onkeydown = function(evt) {...}) or using addEventListener/attachEvent (e.g. button.addEventListener("keydown", function(evt) {...}, false)) then just returning false from that function does not work in every browser and you need to do the returnValue and preventDefault() stuff from my other answer. preventDefault is specified in the DOM 2 spec and is implemented by most mainstream modern browsers. returnValue is IE-specific.
First, if you're detecting a printable character such as space, you would be better off with the keypress event. Secondly, the way to prevent the default action is to call preventDefault() on the event in non-IE browsers and set the event's returnValue property to false in IE.
var button = document.getElementById("button");
button.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
if (charCode == 32) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
};
I'm not a jQuery expert and I assume it takes care of obtaining the event for you:
$("button").keypress(function(evt) {
var charCode = evt.keyCode || evt.which;
if (charCode == 32) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
});
You can just use one attribute in form to stop submit on enter.<form method="post" onkeydown="return false;">
as like: onkeydown="return false;" in form attribute
<form method="post" onkeydown="return false;"></form>
I have a button that fires a "stopstart" function (animation). I also want to have a mouseless method to do this so I've bound the same function to the space bar. This works.
However if focus is on the button, and I press space - both events fire, can't work out how to stop this (the keypress event fires first - in chrome..)
Eventlistener code:
document.getElementById("stopstart").addEventListener("click",
function (event) {
stopstart();
}); //add event listener to "stopstart" button
document.addEventListener("keypress",
function (event) {
if (event.keyCode === 32) { //space key
stopstart();
}
}); //add spacekey event listener to document
I don't want to remove focus from the button, as I'd like to retain that functionality - the two events appear to be separately generated - so I haven't found how to detect that the click event was in fact generated by the space bar.
Is this solvable using without having to add temporary flags to catch it etc
The click location for key events is zero, zero so you can look for that.
document.getElementById("stopstart").addEventListener("click",
function (event) {
var x = event.x || event.clientX;
var y = event.y || event.clientY;
if (!x && !y) {
alert("key press");
return false;
}
stopstart();
});
http://jsfiddle.net/mScEC/
function (event) {
if (event.pointerType !== "mouse") return;
stopstart();
}); //add event listener to "stopstart" button
document.addEventListener("keypress",
function (event) {
if (event.keyCode === 32) { //space key
stopstart();
}
}); //add spacekey event listener to document```
You can simply use event.preventDefault() inside keypress event Listener to prevent the Button Click event from getting triggered on keypress
e.g
document.addEventListener('keydown', function (e) {
e.preventDefault();
if (e.key === 'Enter') {
try {
// if expression is not evaluated then catch block will be executed
screen.value = eval(screen.value);
}
catch (error) {
console.log(error.message);
screen.value = 'Invalid Operation';
}
}
})
How to detect Ctrl+V, Ctrl+C using JavaScript?
I need to restrict pasting in my textareas, end user should not copy and paste the content, user should only type text in textarea.
How can I achieve this?
I just did this out of interest. I agree it's not the right thing to do, but I think it should be the op's decision... Also the code could easily be extended to add functionality, rather than take it away (like a more advanced clipboard, or Ctrl+S triggering a server-side save).
$(document).ready(function() {
var ctrlDown = false,
ctrlKey = 17,
cmdKey = 91,
vKey = 86,
cKey = 67;
$(document).keydown(function(e) {
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;
}).keyup(function(e) {
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;
});
$(".no-copy-paste").keydown(function(e) {
if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false;
});
// Document Ctrl + C/V
$(document).keydown(function(e) {
if (ctrlDown && (e.keyCode == cKey)) console.log("Document catch Ctrl+C");
if (ctrlDown && (e.keyCode == vKey)) console.log("Document catch Ctrl+V");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Ctrl+c Ctrl+v disabled</h3>
<textarea class="no-copy-paste"></textarea>
<br><br>
<h3>Ctrl+c Ctrl+v allowed</h3>
<textarea></textarea>
Also just to clarify, this script requires the jQuery library.
Codepen demo
EDIT: removed 3 redundant lines (involving e.which) thanks to Tim Down's suggestion (see comments)
EDIT: added support for Macs (CMD key instead of Ctrl)
With jquery you can easy detect copy, paste, etc by binding the function:
$("#textA").bind('copy', function() {
$('span').text('copy behaviour detected!')
});
$("#textA").bind('paste', function() {
$('span').text('paste behaviour detected!')
});
$("#textA").bind('cut', function() {
$('span').text('cut behaviour detected!')
});
More information here: http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/
While it can be annoying when used as an anti-piracy measure, I can see there might be some instances where it'd be legitimate, so:
function disableCopyPaste(elm) {
// Disable cut/copy/paste key events
elm.onkeydown = interceptKeys
// Disable right click events
elm.oncontextmenu = function() {
return false
}
}
function interceptKeys(evt) {
evt = evt||window.event // IE support
var c = evt.keyCode
var ctrlDown = evt.ctrlKey||evt.metaKey // Mac support
// Check for Alt+Gr (http://en.wikipedia.org/wiki/AltGr_key)
if (ctrlDown && evt.altKey) return true
// Check for ctrl+c, v and x
else if (ctrlDown && c==67) return false // c
else if (ctrlDown && c==86) return false // v
else if (ctrlDown && c==88) return false // x
// Otherwise allow
return true
}
I've used event.ctrlKey rather than checking for the key code as on most browsers on Mac OS X Ctrl/Alt "down" and "up" events are never triggered, so the only way to detect is to use event.ctrlKey in the e.g. c event after the Ctrl key is held down. I've also substituted ctrlKey with metaKey for macs.
Limitations of this method:
Opera doesn't allow disabling right click events
Drag and drop between browser windows can't be prevented as far as I know.
The edit->copy menu item in e.g. Firefox can still allow copy/pasting.
There's also no guarantee that for people with different keyboard layouts/locales that copy/paste/cut are the same key codes (though layouts often just follow the same standard as English), but blanket "disable all control keys" mean that select all etc will also be disabled so I think that's a compromise which needs to be made.
If you use the ctrlKey property, you don't need to maintain state.
$(document).keydown(function(event) {
// Ctrl+C or Cmd+C pressed?
if ((event.ctrlKey || event.metaKey) && event.keyCode == 67) {
// Do stuff.
}
// Ctrl+V or Cmd+V pressed?
if ((event.ctrlKey || event.metaKey) && event.keyCode == 86) {
// Do stuff.
}
// Ctrl+X or Cmd+X pressed?
if ((event.ctrlKey || event.metaKey) && event.keyCode == 88) {
// Do stuff.
}
}
There's another way of doing this: onpaste, oncopy and oncut events can be registered and cancelled in IE, Firefox, Chrome, Safari (with some minor problems), the only major browser that doesn't allow cancelling these events is Opera.
As you can see in my other answer intercepting Ctrl+V and Ctrl+C comes with many side effects, and it still doesn't prevent users from pasting using the Firefox Edit menu etc.
function disable_cutcopypaste(e) {
var fn = function(evt) {
// IE-specific lines
evt = evt||window.event
evt.returnValue = false
// Other browser support
if (evt.preventDefault)
evt.preventDefault()
return false
}
e.onbeforepaste = e.onbeforecopy = e.onbeforecut = fn
e.onpaste = e.oncopy = e.oncut = fn
}
Safari still has some minor problems with this method (it clears the clipboard in place of cut/copy when preventing default) but that bug appears to have been fixed in Chrome now.
See also: http://www.quirksmode.org/dom/events/cutcopypaste.html and the associated test page http://www.quirksmode.org/dom/events/tests/cutcopypaste.html for more information.
Live Demo :
http://jsfiddle.net/abdennour/ba54W/
$(document).ready(function() {
$("#textA").bind({
copy : function(){
$('span').text('copy behaviour detected!');
},
paste : function(){
$('span').text('paste behaviour detected!');
},
cut : function(){
$('span').text('cut behaviour detected!');
}
});
});
Short solution for preventing user from using context menu, copy and cut in jQuery:
jQuery(document).bind("cut copy contextmenu",function(e){
e.preventDefault();
});
Also disabling text selection in CSS might come handy:
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Another approach (no plugin needed) it to just use ctrlKey property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:
$(document).keypress("c",function(e) {
if(e.ctrlKey)
alert("Ctrl+C was pressed!!");
});
See also jquery: keypress, ctrl+c (or some combo like that).
You can use this code for rightclick, CTRL+C, CTRL+V, CTRL+X detect and prevent their action
$(document).bind('copy', function(e) {
alert('Copy is not allowed !!!');
e.preventDefault();
});
$(document).bind('paste', function() {
alert('Paste is not allowed !!!');
e.preventDefault();
});
$(document).bind('cut', function() {
alert('Cut is not allowed !!!');
e.preventDefault();
});
$(document).bind('contextmenu', function(e) {
alert('Right Click is not allowed !!!');
e.preventDefault();
});
instead of onkeypress, use onkeydown.
<input type="text" onkeydown="if(event.ctrlKey && event.keyCode==86){return false;}" name="txt">
If anyone is interested in a simple vanilla JavaScript approach, see below.
Fiddle Link: DEMO
let ctrlActive = false;
let cActive = false;
let vActive = false
document.body.addEventListener('keyup', event => {
if (event.key == 'Control') ctrlActive = false;
if (event.code == 'KeyC') cActive = false;
if (event.code == 'KeyV') vActive = false;
})
document.body.addEventListener('keydown', event => {
if (event.key == 'Control') ctrlActive = true;
if (ctrlActive == true && event.code == 'KeyC') {
// this disables the browsers default copy functionality
event.preventDefault()
// perform desired action(s) here...
console.log('The CTRL key and the C key are being pressed simultaneously.')
}
if (ctrlActive == true && event.code == 'KeyV') {
// this disables the browsers default paste functionality
event.preventDefault()
// perform desired action(s) here...
console.log('The CTRL key and the V key are being pressed simultaneously.')
}
})
The code above would disable the default copy in the browser. If you'd like keep the copy functionality in the browser, just comment out this bit: event.preventDefault() and you can then run any desired actions while allowing the user to copy content.
I wrote a jQuery plugin, which catches keystrokes. It can be used to enable multiple language script input in html forms without the OS (except the fonts). Its about 300 lines of code, maybe you like to take a look:
http://miku.github.com/jquery-retype
Generally, be careful with such kind of alterations. I wrote the plugin for a client because other solutions weren't available.
Don't forget that, while you might be able to detect and block Ctrl+C/V, you can still alter the value of a certain field.
Best example for this is Chrome's Inspect Element function, this allows you to change the value-property of a field.
A hook that allows for overriding copy events, could be used for doing the same with paste events. The input element cannot be display: none; or visibility: hidden; sadly
export const useOverrideCopy = () => {
const [copyListenerEl, setCopyListenerEl] = React.useState(
null as HTMLInputElement | null
)
const [, setCopyHandler] = React.useState<(e: ClipboardEvent) => void | null>(
() => () => {}
)
// appends a input element to the DOM, that will be focused.
// when using copy/paste etc, it will target focused elements
React.useEffect(() => {
const el = document.createElement("input")
// cannot focus a element that is not "visible" aka cannot use display: none or visibility: hidden
el.style.width = "0"
el.style.height = "0"
el.style.opacity = "0"
el.style.position = "fixed"
el.style.top = "-20px"
document.body.appendChild(el)
setCopyListenerEl(el)
return () => {
document.body.removeChild(el)
}
}, [])
// adds a event listener for copying, and removes the old one
const overrideCopy = (newOverrideAction: () => any) => {
setCopyHandler((prevCopyHandler: (e: ClipboardEvent) => void) => {
const copyHandler = (e: ClipboardEvent) => {
e.preventDefault()
newOverrideAction()
}
copyListenerEl?.removeEventListener("copy", prevCopyHandler)
copyListenerEl?.addEventListener("copy", copyHandler)
copyListenerEl?.focus() // when focused, all copy events will trigger listener above
return copyHandler
})
}
return { overrideCopy }
}
Used like this:
const customCopyEvent = () => {
console.log("doing something")
}
const { overrideCopy } = useOverrideCopy()
overrideCopy(customCopyEvent)
Every time you call overrideCopy it will refocus and call your custom event on copy.
Another simple way using Jquery:
$(document).keydown( function(e)
{
if (e.ctrlKey && e.key == 'c')
{
console.log('got ctrl c');
}
else if (e.ctrlKey && e.key == 'v')
{
console.log('got ctrl v');
}
});
element.addEventListener('keydown', function (e) {
if (e.key == 'c' && e.ctrlKey) {
e.preventDefault(); // prevent from copying
}
if (e.key == 'v' && e.ctrlKey) {
e.preventDefault(); // prevent from pasting
}
}
i already have your problem and i solved it by the following code .. that accept only numbers
$('#<%= mobileTextBox.ClientID %>').keydown(function(e) {
///// e.which Values
// 8 : BackSpace , 46 : Delete , 37 : Left , 39 : Rigth , 144: Num Lock
if (e.which != 8 && e.which != 46 && e.which != 37 && e.which != 39 && e.which != 144
&& (e.which < 96 || e.which > 105 )) {
return false;
}
});
you can detect Ctrl id e.which == 17
Important note
I was using e.keyCode for a while and i detected that when i press Ctrl+., This attribute returns a wrong number, 190, while the ascii code of . is 46!
So you should use e.key.toUpperCase().charCodeAt(0) instead of e.keyCode.
$(document).keydown(function(event) {
let keyCode = e.key.toUpperCase().charCodeAt(0);
...
}
You can listen to the keypress event, and halt the default event (entering the text) if it matches the specific keycodes
There is some ways to prevent it.
However the user will be always able to turn the javascript off or just look on the source code of the page.
Some examples (require jQuery)
/**
* Stop every keystroke with ctrl key pressed
*/
$(".textbox").keydown(function(){
if (event.ctrlKey==true) {
return false;
}
});
/**
* Clear all data of clipboard on focus
*/
$(".textbox").focus(function(){
if ( window.clipboardData ) {
window.clipboardData.setData('text','');
}
});
/**
* Block the paste event
*/
$(".textbox").bind('paste',function(e){return false;});
Edit: How Tim Down said, this functions are all browser dependents.
I have a button and the following javascript routine.
$("button").keydown( function(key) {
switch(key.keyCode) {
case 32: //space
return false;
}
} );
as I understood it, the return false; would stop the keypress from being processed. So $("button").click(); would not be called. For other keyCodes, this works as expected. For example, if I intercept40, which is the down button, the page is not scrolling.
I noticed this behavior in Firefox.
Why does the return false; does not stop the button click event on space? What does the javascript spec say about this?
Hope this answers your question:
<input type="button" value="Press" onkeydown="doOtherStuff(); return false;">
return false; successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML. This behaviour is not formally specified anywhere as far as I know.
If you instead set an event via an event handler property on the DOM element (e.g. button.onkeydown = function(evt) {...}) or using addEventListener/attachEvent (e.g. button.addEventListener("keydown", function(evt) {...}, false)) then just returning false from that function does not work in every browser and you need to do the returnValue and preventDefault() stuff from my other answer. preventDefault is specified in the DOM 2 spec and is implemented by most mainstream modern browsers. returnValue is IE-specific.
First, if you're detecting a printable character such as space, you would be better off with the keypress event. Secondly, the way to prevent the default action is to call preventDefault() on the event in non-IE browsers and set the event's returnValue property to false in IE.
var button = document.getElementById("button");
button.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
if (charCode == 32) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
};
I'm not a jQuery expert and I assume it takes care of obtaining the event for you:
$("button").keypress(function(evt) {
var charCode = evt.keyCode || evt.which;
if (charCode == 32) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
});
You can just use one attribute in form to stop submit on enter.<form method="post" onkeydown="return false;">
as like: onkeydown="return false;" in form attribute
<form method="post" onkeydown="return false;"></form>
I have multiple fields, typically enter will be pressed on one of the two main ones. I want to know which field enter has been pressed on, how do i do this? (i dont know much JS)
its simple to add an "onkeypress" event to each of the fields, and then in the event handler to examine the keycode that is attached to the event. For example, consider the following code:
form.elements['fieldone'].onkeypress = function(evt) {
if (window.event) evt = window.event; // support IE
if (evt.keyCode == 13) alert("Enter was pressed!");
return true;
}
Please note that under most browsers, pressing ENTER in a form field would post that form. If you don't want that to happen, you can simply return false from the onkeypress handler and that would tell the browser to ignore that key.
Check for enter and set some hidden field (example uses JQuery):
$('#input_text').keyup(function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
alert('Enter key was pressed.');
}
});
Include this in your page, it should fire automatically when you hit any key and tell you which html element had focus when it happened.
<script>
document.onkeypress = KeyPressed;
function KeyPressed(e)
{
if (!e) e = window.event;
f ((e.charCode) && (e.keyCode == 13))
alert('Yay! Enter was pressed while field ' + document.activeElement.id + ' had focus!');
}
</script>
You can check from which element the event bubbled from using something like the following
var text1 = document.getElementById('text1');
var text2 = document.getElementById('text2');
text1.onkeypress = keyPresser;
text2.onkeypress = keyPresser;
function keyPresser(e) {
// to support IE event model
var e = e || window.event;
var originalElement = e.srcElement || e.originalTarget;
if (e.keyCode === 13) {
alert(originalElement.id);
}
}
Here's a Working Demo
I would recommend taking a look at the differences in Browser event models and also at unobtrusive JavaScript .
QuirksMode - Introduction to Events
The IE Event Model
Pro JavaScript Techniques - Unobtrusive Event Binding
Use event delegation to avoid attaching event handlers to a large number of elements:
window.onload = function () {
document.onkeyup = function (e) {
e = e || window.event;
var target = e.target || e.srcElement,
keyCode = e.keyCode || e.which;
if (target.tagName.toLowerCase() == 'input' && keyCode == 13) {
alert('Enter pressed on ' + target.id);
}
};
};