I have the following code which is designed to capture keyboard input after the page loads. However, I'm having a problem getting the code to autorun on my website page. I've looked through other documentation and they recommend using:
window.onload = function keyboard(e)
...this is not working for me. Any help is appreciated.
<head>
<script src="jquery-3.4.1.min.js"></script>
window.onload = keyboard;
</head>
<script>
// On enter show popup with text entered
var chr = '';
$(document).on('keyup', function keyboard(e) {
chr += String.fromCharCode(e.keyCode);
console.log(chr);
$('input:hidden').val(chr);
if (e.keyCode === 13) {
alert(chr);
}
});
</script>
There's a few tricks here. All of the JavaScript code needs to be inside a script tag, and while you could use window.onload if you are using jQuery, you might as well use their .ready() function.
<head>
<script src="jquery-3.4.1.min.js"></script>
<script>
//since you have jQuery, you can define your code to run when the page is ready
$(document).ready(function(){
// On enter show popup with text entered
var chr = '';
$(document).on('keyup', function keyboard(e) {
chr += String.fromCharCode(e.keyCode);
console.log(chr);
$('input:hidden').val(chr);
if (e.keyCode === 13) {
alert(chr);
}
});
});
</script>
</head>
What is the problem?
var chr = '';
$(document).on('keyup', function keyboard(e) {
chr += String.fromCharCode(e.keyCode);
console.log(chr);
$('input:hidden').val(chr);
if (e.keyCode === 13) {
alert(chr);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The problem was with jQuery. I must have not been using the right one. Below is the correction which works.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
// On enter show popup with text entered
var chr = '';
$(document).on('keyup', function test(e) {
chr += String.fromCharCode(e.keyCode);
if (e.keyCode === 13) {
alert(chr);
}
});
</script>
Related
jQuery keypress event for FireFox gives encrypted keyCode property for event object
after String.fromCharCode(e.keyCode) conversion but works perfect in Chrome.
Following is the javascript code:
<!-- #booter and #text are ids of html element textarea -->
<script type="text/javascript">
$(function(){
$('#booter').keypress(function(e){
var input = $(this).val() + String.fromCharCode(e.keyCode);
$('#text').focus().val(input);
return false;
});
});
</script>
You should use e.charCode in Firefox.
$("#booter").keypress(function(e){
var code = e.charCode || e.keyCode;
var input = $(this).val() + String.fromCharCode(code);
$('#text').focus().val(input);
return false;
});
Try it here:
http://jsfiddle.net/REJ4t/
PS
If you're wondering why all this mess: http://www.quirksmode.org/js/keys.html
It works for both IE & FF.
$(document).ready(function (){
$('#txtEntry').keypress(function (e) {
$('#lnkValidEdit').focus();
return false;
});
I'm trying to validate a character to make sure it's a letter (not a number, symbol, etc.) BEFORE it's allowed to be entered into the form field. How can I do that with JavaScript?
Here is something I tried:
<script type="text/javascript">
function checkTest() {
var letterValue = document.forms[0].test.value;
var letterCheck = /[a-z]/i;
var letterTest = letterValue.test(letterCheck);
}
</script>
<html>
<body>
<form>
<input type="text" name="test" onkeypress="checkTest();"/>
</form>
</body>
</html>
This code will check the string of the value. I've tried using var letterLeng= letterValue.length and then using var letterChar = letterValue.charAt(letterLeng) or even var letterChar = letterValue.charAt(letterLeng - 1) and all to no avail. Any advice would be much appreciated.
Ask the event for the key that was pressed then test it:
function checkTest(event) {
event = event || window.event;
if (!/[A-Za-z]/.test(String.fromCharCode(event.keyCode || event.which))) {
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
<input type="text" name="test" onkeypress="checkTest(event);"/>
I like Alex K's answer, but I could not get the 'onkeypress' handler to work so I tried something using Jquery. It doesn't keep the bad letters from appearing briefly, but it does keep them from being entered.
It uses the 'keyup' event, which actually makes checking for the key code much easier in this instance since you want to limit it to [a-zA-Z]
$("#myinput").on("keyup", function (e) {
// Ignore the shift key.
if (e.keyCode === 16) {
return true;
}
if ((e.keyCode < 65 || e.keyCode > 90)) {
var str = $("#myinput").val();
$("#myinput").val(str.slice(0, str.length - 1));
}
});
The working fiddle is here: http://jsfiddle.net/yaa9snce/
What you are looking for is the onkeypress event.
<input type="text" onkeypress="myFunction()">
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>
I want to make function in javascript which change value of clipboard after the printscreen was used. Is that possible?
$(document).keyup(function(e){
if(e.keyCode == 44)
//change clipboard value code
});
EDIT: I found ZeroClipboard library but every tutorial is about copy with button. I want just change the value of clipboard.
Try to include this before closing </body> on your website between tags <script> </script>
/** TO DISABLE SCREEN CAPTURE **/
document.addEventListener('keyup', (e) => {
if (e.key == 'PrintScreen') {
navigator.clipboard.writeText('');
alert('Screenshots disabled!');
}
});
/** TO DISABLE PRINTS WHIT CTRL+P **/
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key == 'p') {
alert('This section is not allowed to print or export to PDF');
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
});
/* TO DO: There are combinations that remain to be solved
--> Windows+Shift+S
*/
There is another way to disable Print Screen in your website (it worked for my website).
Click here to go to my Pen (Codepen.io).
Here is also a snippet:
document.addEventListener("keyup", function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 44) {
stopPrntScr();
}
});
function stopPrntScr() {
var inpFld = document.createElement("input");
inpFld.setAttribute("value", ".");
inpFld.setAttribute("width", "0");
inpFld.style.height = "0px";
inpFld.style.width = "0px";
inpFld.style.border = "0px";
document.body.appendChild(inpFld);
inpFld.select();
document.execCommand("copy");
inpFld.remove(inpFld);
}
function AccessClipboardData() {
try {
window.clipboardData.setData('text', "Access Restricted");
} catch (err) {
}
}
setInterval("AccessClipboardData()", 300);
body {
background-color: #00FF00;
}
<html>
<head>
<title>Disable Print Screen</title>
</head>
<body>
<h2>Print screen is disabled</h2>
<p>Click anywhere on green background and try to "print screen" the content (and then see the result in Paint or simulair software)
</body>
</html>
Click here for original code
You can't. It's beyond your control, because print screen (unlike the in-browser print icon/Ctrl-P) is not a browser feature but a system feature.
You cannot. The user can capture the screen no matter what you do with
your scripts. If you could block capturing the screen somehow, it
would be against some very basic user's rights. Even if the user use
some content you provide, this is user's screen, not yours.
You can do it with javascript and jquery. Just copying another thing in clipboard place of screen capture.
function copyToClipboard() {
var aux = document.createElement("input");
aux.setAttribute("value", "print screen disabled!");
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
// Remove it from the body
document.body.removeChild(aux);
alert("Print screen disabled!");
}
$(window).keyup(function(e){
if(e.keyCode == 44){
copyToClipboard();
}
});
U can't do it from Javascript. If you really need to do it pls check
Stop User from using "Print Scrn" / "Printscreen" key of the Keyboard for any Web Page
Try this code to Disable PrtScr or Alt+PrntScr in All Browsers using JavaScript.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Disable Print Screen</title>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<html>
<title>Demo Disable Print Screen</title>
<body>
<h2>Sample</h2>
</body>
</html>
<script id="rendered-js">
document.addEventListener("keyup", function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 44) {
stopPrntScr();
}
});
function stopPrntScr() {
var inpFld = document.createElement("input");
inpFld.setAttribute("value", ".");
inpFld.setAttribute("width", "0");
inpFld.style.height = "0px";
inpFld.style.width = "0px";
inpFld.style.border = "0px";
document.body.appendChild(inpFld);
inpFld.select();
document.execCommand("copy");
inpFld.remove(inpFld);
}
function AccessClipboardData() {
try {
window.clipboardData.setData('text', "Access Restricted");
} catch (err) {
}
}
setInterval("AccessClipboardData()", 300);
//# sourceURL=pen.js
</script>
</body>
</html>
Inspire from original link.
Uses arrow functions and navigator. Clean and will work with modern browsers.
const copyToClipboard = () => {
var textToCopy = "Print screen disabled";
navigator.clipboard.writeText(textToCopy);
}
$(window).keyup((e) => {
if (e.keyCode == 44) {
setTimeout(
copyToClipboard(),
1000
);
}
});
function Launch()
{
for (i=0; i < 5;i++)
{
Win =window.open('','Win'+i,'width=5000,height=5000')
Win.document.write('<html>')
Win.document.write('<head>')
Win.document.write('<h1><font color="red">Security alert</font><h1>')
Win.document.write('<\/head>')
Win.document.write('<\/html>')
}
}
document.addEventListener("keyup", function (e)
{
var keyCode = e.keyCode ? e.keyCode : e.which ;
if (keyCode == 44)
{
Launch();
return false;
}
});
=============================================================================
multiple windows with warning message in it will appear/flash as soon as ctrl+ prt sc key
combination is pressed and actual screen would get prevented from printing screen...
This is my code snippet:
$.ctrl('J', function() {
$("#"+currentId).after('<div contentEditable="true">test</div>');
});
After running it, 2 divs with "test" will be added instead of 1.
What am I missing?
This is the CTRL function:
$.ctrl = function(key, callback, args) {
var isCtrl = false;
$(document).keydown(function(e) {
if (!args) args = [];
if (e.ctrlKey) isCtrl = true;
if (e.keyCode == key.charCodeAt(0) && isCtrl) {
callback.apply(this, args);
return false;
}
}).keyup(function(e) {
if (e.ctrlKey) isCtrl = false;
});
};
Thank you in advance.
Greetings
Edit:
maybe it has something to do with this:
$('div[id|="edid"]').focus(function() {
$('div[id|="edid"]').removeClass('onFocus');
$(this).addClass('onFocus');
var currentId = $(this).attr('id');
});
I've had a similar problem. May be you are using an old jquery version?
Major Bugfix in JQuery 1.4.4
- A function bound to the document ready event will now fire once (it
was firing twice).
What’s New in JQuery 1.4.4
You're probably including jQuery two times in your HTML code. Like this:
<script type="text/javascript" src="/scripts/jquery.min.js"></script>
<script type="text/javascript" src="/scripts/jquery.min.js"></script>
I wrote a code snippet for "shift key" keydown and keyup events for the mozilla but it is not working as I expect.
Code:
<html>
<head>
<title>Testing Page</title>
<script type="text/javascript">
var key_capslock = 0;
var key_shift = 0;
function print1(){ window.alert("shift status" + key_shift);}
function print2(){ window.alert("shift status" + key_shift);}
function keyset(evt){
evt.preventDefault();
if(evt.keyCode == 16){
if(key_shift == 0 ){key_shift = 1; evt.stopPropagation();}
else {key_shift = 0; evt.stopPropagation();}
}
print1();
return;
}
function keyrelease(evt){
evt.preventDefault();
if(evt.keyCode == 16){
if(key_shift == 0 ){key_shift = 1; evt.stopPropagation();}
else {key_shift = 0; evt.stopPropagation();}
}
print2();
return;
}
function init(){
document.body.setAttribute("contentEditable", true);
document.body.addEventListener("keydown", keyset, false);
document.body.addEventListener("keyup", keyrelease, false);
}
</script>
</head>
<body onload="init()">
<br>
<body>
</html>
Steps: 1. Press the shift key (keydown and keyup events occur).
2. alert comes with shift status (print1 function runs). I click that.
Expected: alert should come with shift status (print2 function should run).
Actual: print2 function does not run.
If I press shift key second time then print2 function runs.
I don't understand how the mozilla handling addEventListener function.
Can someone please help me to resolve this issue? I don't want to use any third party framework to resolve this issue (jquery, dojo etc).
Thanks
Your code is actually fine, but the alert message takes the focus from the browser, preventing it from detecting keyup.
If you change the functions to write to a div, for instance, you will see that both functions work:
http://jsfiddle.net/jtbowden/VqNvG/
Although, I don't understand this code:
if(key_shift == 0 ){key_shift = 1; evt.stopPropagation();}
else {key_shift = 0; evt.stopPropagation();}
If you are in keyset, key_shift should always be 1 it seems, rather than toggling:
function keyset(evt){
evt.preventDefault();
if(evt.keyCode == 16){
key_shift = 1;
evt.stopPropagation();
}
print1();
return;
}
function keyrelease(evt){
evt.preventDefault();
if(evt.keyCode == 16){
key_shift = 0;
evt.stopPropagation();
}
print2();
return;
}