disable KeyBoard shortcuts on JWPlayer - javascript

We want to disable Keyboard shortcuts to fast forward and seek another position.
Javascript disabled keys are working when it is not in fullscreen but we are facing issues when it is full screen.
Is it possible to turn off keyboard shortcuts?

Here is a code demo that demonstrates how to disable the left and right keyboard arrow keys:
jwplayer('player').on('ready', () => {
// BLOCKING LEFT and RIGHT KEY PRESS
let all = document.getElementsByTagName('*');
for (let element of all) {
element.addEventListener("keydown", (e) => {
if ((e.which || e.keyCode) == 37) {
e.stopImmediatePropagation();
};
if ((e.which || e.keyCode) == 39) {
e.stopImmediatePropagation();
};
}, true);
}
});

Here is a more succinct approach that targets the jwplayer element(s) directly and disables all keyboard shortcuts:
document.querySelectorAll('.jwplayer').forEach(elem => {
elem.addEventListener('keydown', (e) => e.stopImmediatePropagation(), true);
});

Related

Escape key pressing not run keydown event [duplicate]

Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode

Detecting Alt key in Chrome

In my app I need to handle Alt key press/release to toggle additional information on tooltips. However, the first time Alt is pressed, document loses keyboard focus, because it goes to Chrome's menu. If I click any part of the document, it works again (once).
I can avoid this by calling preventDefault, but that also disables keyboard shortcuts such as Alt+Left/Right, which is undesirable.
I can also handle mousemove and check altKey flag, but it looks very awkward when things only update when mouse is moved.
Is there any way to reliably detect current Alt key state in my situation? I would really rather not switch to a different key.
Update: I suppose the best solution would be to call preventDefault only when a tooltip is active.
document.addEventListener("keydown", (e) => {
if (this.curComponent) e.preventDefault();
if (e.which === 18) {
this.outer.classList.add("AltKey");
}
});
document.addEventListener("keyup", (e) => {
if (this.curComponent) e.preventDefault();
if (e.which === 18) {
this.outer.classList.remove("AltKey");
}
});
I had the same issue and I solved thanks to this answer:
document.addEventListener("keyup", (e) => {
if (e.key === "Alt") {
return true; // Instead of e.preventDefault();
});
return true restores normal behavior of Alt+Left/Right chrome keyboard shortcuts.
Keyboard value both left/ right side ALT = 18
jQuery:
$(document).keyup(function(e){
if(e.which == 18){
alert("Alt key press");
}
});
JavaScript
document.keyup = function(e){
if(e.which == 18){
alert("Alt key press");
}
}

On CTRL+MOUSEWHEEL event

I was asked to implement ctrl+mousewheel event for our page site in order to change image offset on user zoom in or zoom out. I found this old answer Override browsers CTRL+(WHEEL)SCROLL with javascript and I`ve tried to do the same.
I downloaded the jQuery Mouse Wheel Plugin for the implementation and here is my code:
var isCtrl = false;
$(document).on('keydown keyup', function(e) {
if (e.which === 17) {
isCtrl = e.type === 'keydown' ? true : false;
}
}).on('mousewheel', function(e, delta) { // `delta` will be the distance that the page would have scrolled;
// might be useful for increasing the SVG size, might not
if (isCtrl) {
e.preventDefault();
alert('wheel');
}
});
The events works fine separately, but if I hold the CTRL button and wheel the mouse the wheel event does not fire.
Does any one have better solution for this or may be I did something wrong?
Fiddle, In order for it to work you have to click in the result box first before trying.
$(window).bind('mousewheel DOMMouseScroll', function(event)
{
if(event.ctrlKey == true)
{
event.preventDefault();
if(event.originalEvent.detail > 0) {
console.log('Down');
}else {
console.log('Up');
}
}
});
To check if the ctrl key is clicked, the event already provides a way to do that. Try this:
.on('mousewheel', function(e) {
if (e.ctrlKey) {
e.preventDefault();
alert('wheel');
}
});
This also works for e.shiftKey, e.altKey etc. I would only listen for the scroll event and there I would check if the ctrlKey is down.
This can be achieved with the wheel event, which is the standard wheel event interface to use.
document.getElementById('id_of_element')
.addEventListener('wheel', (e) => {
if(e.ctrlKey)
alert("Control + mouse wheel detected!");
})

Prevent window scroll jquery

I'm developing a select menu replacement in jquery.
First I've to make the new select menu focusable by just adding tabindex="0" to the container.
Then, I disable focus on the original select menu and give focus to the new one.
When the new one is focused and you press the up and down arrows the options change accordingly but there's a big problem. As you press the arrows the body moves too.
I tried all these solutions so far with no luck:
$(window).unbind('scroll');
$(document).unbind('scroll');
$('body').unbind('scroll');
$(window).unbind('keydown');
$(document).unbind('keydown');
Check the code here http://pastebin.com/pVNMqyui
This code is from the development version of Ideal Forms http://code.google.com/p/idealforms that I'm about to release soon, with keyboard support.
Any ideas why this is not working?
EDIT: Solved!
Found the answer on this post jquery link tag enable disable
var disableScroll = function(e){
if (e.keyCode === 40 || e.keyCode === 38) {
e.preventDefault();
return false;
}
};
// And then...
events.focus: function(){ $(window).on('keydown', disableScroll); }
events.blur: function(){ $(window).off('keydown', disableScroll); }
It works!
In your keydown handler, for up and down keys, return false like this:
'keydown' : function (e) {
if (e.keyCode === 40) { // Down arrow
that.events.moveOne('down');
}
if (e.keyCode === 38) { // Up arrow
that.events.moveOne('up');
}
return false;
}
Also, make sure this return gets propagated to the browser's native onkeydown depending on how/which framework you're using.
Found the answer on this post jquery link tag enable disable
var disableScroll = function(e){
if (e.keyCode === 40 || e.keyCode === 38) {
e.preventDefault();
return false;
}
};
// And then...
events.focus: function(){ $(window).on('keydown', disableScroll); }
events.blur: function(){ $(window).off('keydown', disableScroll); }
You need to cancel the keydown event for arrow keys. Use either e.preventDefault() or return false in your .keydown() handler if an arrow key has been pressed.
Its very simple.you need not even need jQuery for this.
jQuery:
$("body").css("overflow", "hidden");
javascript
<body style="overflow: hidden">
Adding in style:
<style>
body {width:100%; height:100%; overflow:hidden, margin:0}
html {width:100%; height:100%; overflow:hidden}
</style>
if you want to bind the arrow keys,try something like:
$('body').keydown(function(e){
e.preventDefult();
if(e.keyCode == 37) // for left key
{
// implement focus functionality
}
if(e.keyCode == 38) // for up key
{
// implement focus functionality
}
if(e.keyCode == 39) // for right key
{
// implement focus functionality
}
if(e.keyCode == 40) // for doqn key
{
// implement focus functionality
}
});
The Best way to achive the same is to set overflow of the body to hidden
$("body").css("overflow", "hidden");
After the process just do the opposite
`$("body").css("overflow", "hidden");

How to detect Ctrl+V, Ctrl+C using JavaScript?

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.

Categories