I'm building this simple JavaScript project where if I input number N then it will show 1 to N. I'm using keyup() event for this. If I remove N from the input field then It will show nothing, which is fine! Because I'm using the empty() function. It works for 1-9. But when I input 10, 11, 12... it first shows 1 then it shows 1 to 10 or 1 to 11 accordingly. I only need to see 1 to N(more than single-digit). I don't want to use button for this.
Here is my code:
$(document).ready(function() {
$('#code').keyup(function() {
let myCode = $('#code').val();
if (myCode == '') {
$('#output').empty();
}
for (let i = 1; i <= myCode; i++) {
$('#output').append(i + '<br>');
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="number" id="code">
<br>
<br>
<div id="output"></div>
</body>
</html>
If this problem has better solution kindly share.
You need to use the concept of debouncing using setTimeout.
Your event is getting fired twice, once when you press '1' and when you press '0'. You need to hold the event until you are done with entering the numbers. The below code would work
var timer;
$(document).ready(function() {
$('#code').keyup(function() {
clearTimeout(timer)
timer = setTimeout(function(){let myCode = $('#code').val();
if (myCode == '') {
$('#output').empty();
}
for (let i = 1; i <= myCode; i++) {
$('#output').append(i + '<br>');
}},1000)
})
});
As Barmar pointed out in the comments, you need to reset the output every time the event is fired.
The keyup event happens immediately after the release a keyboard key.
So your listener function is executed every digit you enter (after the release of the key).
So if you insert 155, it first will append number to 1-1, then from 1-15 (because when you type the second digit and release the key (event fired) your input contains 15), and at last digit it will print number from 1- to the current input value that is 155 (input contains 155) and so on if you add digits.
Thus your code would be:
$(document).ready(function () {
$('#code').on('keyup', function () {
let myCode = $('#code').val();
// when event happens reset the output field, so it is overridden with the new serie
$('#output').empty();
for (let i = 1; i <= myCode; i++) {
$('#output').append(`${i}<br>`);
}
});
});
Small suggestions:
Use a "buffer" for the output because the append method is a bit expensive to call every cycle. Better build the string apart and append it when you're done.
Use the input event, it's more semantic and related to input tag. And the event is fired whenever the input content change, so it's more immediate.
$(document).ready(function () {
$('#code').on('input', function () {
let myCode = $('#code').val();
$('#output').empty();
let string = '';
for (let i = 1; i <= myCode; i++) {
string += `${i}<br>`;
}
$('#output').append(string);
});
});
Related
Edited:
I forgot to add a 'native' (for JS or browser) word to questions, as browsers (or JS i'm not sure) have a undo/redo feature in inputs, but it don't work with programmatically edited input and my main question is, if it is possible to add a code to trigger that native callback to previous value feature.
I tried to do this with document.execCommand paste/insertText but it didn't work and is marked as obsolete.
Old:
I have a custom action on keypress in input, for example where number have changed sign(+-) when '-' button is pressed.
I want to add that action to native undo/redo (ctrl+z/y) history stack, with preventing others default actions triggered when button responsible for my action is clicked.
Is this possible?
If no, to remove current, native undo/redo input feature, using event.preventDefault in crtl+z/y click detection would be enough? To replace it by custom undo/redo.
Is this dependable on browser?
I experimented with code on Firefox and Edge.
Is there something like History API for input available for JS and where i can read about it and how it is named in code?
As for similar topics in stack are old and i tried them but they didn't work (or i used them in wrong way).
$(document).ready(function() {
$(":input").on('keypress', function(e) {
//On minus button click, reverse sign for number in input:
if (e.key === '-') {
e.preventDefault();
//TODO: Add this change in input to undo/redo changes history:
$(this).val(-$(this).val());
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Number: <input type="text" name="num"><br>
</body>
</html>
i3z slighty enchanted answer:
Ctrl+z instead of '-' button for Undo action.
Fixed bug with 2 clicks needed to use undo action after adding new element.
Sign change action from my question is added to code.
Added empty "" as default in history stack.
// Global Varaibles
// Edited: Added empty undo element, fixed undo working from 2nd click after adding new element to history.
var historyValues = [''];
var undoSteps = 2;
var maxSteps = 1;
var currentUndo = 1;
// Add event listener to track input and update historyValues
$(":input").on('input', function (evt) {
historyValues.push(this.value);
maxSteps = historyValues.length;
//console.log(historyValues);
// Check if 'Undo' been used if yes reset cause input been changed
if (undoSteps !== 2) {
undoSteps = 2;
}
});
$(document).ready(function() {
$(":input").on('keydown', function(e) {
if (undoSteps > maxSteps) {
// When you run out of backward steps, reset steps
undoSteps = 1;
}
// check for key (Edited: changed to z) and ensure 'currentUndo' not less than 0
if (e.ctrlKey && e.key === 'z' && currentUndo >= 0) {
e.preventDefault();
// tracking steps backward for every-time key '-' pressed
currentUndo = (maxSteps - undoSteps);
//console.log(maxSteps+' maxSteps - undoSteps '+undoSteps);
// Get previous value from history array
var newValue = historyValues[currentUndo];
//console.log(currentUndo+' current - value '+newValue);
$(this).val(newValue);
// Add +1 steps as we used undo once
undoSteps++;
}
});
$(":input").on('keypress', function(e) {
//Edited: Added custom action on key '-' press
if (e.key === '-') {
e.preventDefault();
$(this).val(-$(this).val());
//Trigger history
$(this).trigger('input');
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Number: <input type="text" name="num"><br>
</body>
</html>
Simple Undo JS Script
You'll be able to capture event of (⌘ + z) or (CTRL + z). Therefore, you'll be able to preform this Undo JS implementation to have history stack of values every-time input changes.
You should have Event Listener (input) either via DOM or jQuery e.g.
$(":input").on('input', function (evt) {
console.log(this.value)
}
Now, you can trace any changes in input been targeted using jQuery Selector.
You should also define global variables inside your document, where you can track following:
History Stack (historyValues)
Steps To Take (undoSteps)
Maximum Steps (maxSteps)
Current Step (currentUndo)
Source Code
// Global Varaibles (Controls)
var historyValues = [''];
var undoSteps = 2;
var maxSteps = 1;
var currentUndo = 1;
// Add event listener to track input changes and update historyValues
$(":input").on('input', function (evt) {
historyValues.push(this.value);
maxSteps = historyValues.length;
//console.log(historyValues);
// Check if 'Undo' been used if yes reset cause input been changed
if (undoSteps !== 2) {
undoSteps = 2;
}
});
$(document).ready(function() {
$(":input").on('keydown', function(e) {
if (undoSteps > maxSteps) {
// When you run out of backward steps, reset steps
undoSteps = 1;
}
// Edited: Supports (⌘ + z and CTRL + z)
if ( (e.ctrlKey && e.key === 'z') || (e.metaKey && e.key === 'z') ) {
e.preventDefault();
// Ensure 'currentUndo' not less than 0
if (currentUndo >= 0) {
// tracking steps backward
currentUndo = (maxSteps - undoSteps);
// Get previous value from history array
var newValue = historyValues[currentUndo];
$(this).val(newValue);
// Add +1 steps as we used undo once
undoSteps++;
}
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Number: <input type="text" name="num"><br>
</body>
</html>
I'm trying to create a chrome extension that clicks a button on a website using the DOM.click() method. (https://www.w3schools.com/jsref/met_html_click.asp)
EDIT: The purpose of this chrome extension is to create a keyboard shortcut to toggle on/off English Subtitles while watching a foreign language video. Having to use your mouse and dragging it to open a menu to turn on subtitles when you need them can be inconvenient if you are trying to understand the language without the subtitles. I wanted to create a keyboard shortcut that would immediately turn on the subtitles. An example of such a website is
(https://www.ondemandkorea.com/ask-us-anything-e102.html)
<button type="button" class="jw-reset jw-settings-content-item" role="menuitemradio" aria-checked="false">English</button>
This is button on the website I'm trying to click with Javascript
In my code, I have a window listener that waits for the specific website to load. Then, to find the button I want to click, I call document.getElementsByClassName("Class Name") and look through the returned elements array for a button that that says English and save it into var englishButton. I add another listener that listens for a keyboard key to be pressed which in turn presses englishButton.
However, when I click the shortcutKey, englishButton.click(); doesn't seem to do anything. I know that the correct English Button is found and that my shortcutKey Listener works through the use of console.log() statements.
I can't seem to understand why the button won't click.
EDIT: After adding a buttonListener to the code, the English button does click after all, but it does not turn on the subtitles for the video
Here's my code.
/*
Looking for the subtitle button that states "English"
*/
var englishButton;
window.addEventListener("load", function(event) {
var buttonList = document.getElementsByClassName('jw-reset jw-settings-content-item');
for (var i = 0, len = buttonList.length; i < len; i++){
if(buttonList[i].textContent === "English") {
englishButton = buttonList[i];
break;
}
}
englishButton.addEventListener('click', function() {
console.log('englishButton clicked!');
});
/*
Event Listener that detects when the shortcut key is hit.
When the shortcut Key is hit. It will simulate a mouse click on the subtitle button
*/
document.addEventListener('keyup', function(e){
if(e.key === shortcutKey){
console.log('shortcut pressed')
englishButton.click();
}
}
);
});
In your comments under your question, you confirmed that the button is actually triggering the click. So the issue for you is rather producing the intended result from the click. Which is to toggle on and off the English caption. There's a better, simpler, and much more reliable alternative here.
The website uses JW Player to show its video. They have a well-documented and open API (https://developer.jwplayer.com/jw-player/docs/developer-guide).
All you have to do is something like this
jwplayer().setCurrentCaptions(X)
Here X is the index number of the caption option you want to select from within the list of all captions that are available in a particular video.
In your example video, the list has only two items:
0: Off
1: English
So to turn on English:
jwplayer().setCurrentCaptions(1)
And to turn off all caption:
jwplayer().setCurrentCaptions(0)
If the index would vary from one video to another, you need to first get the list of captions available and then find the index number for English.
let allCaptions = jwplayer().getCaptionsList();
englishCaptionIndex = allCaptions.findIndex(caption => caption.label == 'English');
That's it.
You can do all kinds of interesting things using the API.
I recommend you to use jQuery, so you can use functions like keyup() or keydown() so you can listen when a key is pressed. Also a better practice is to check the element by id if we only want to watch over a DOM element instead of using a class.
Move all your code into your load listener:
https://codepen.io/ryanpcmcquen/pen/EOerPM?editors=1011
window.addEventListener("load", function(event) {
/*
Looking for the subtitle button that states "English"
*/
var englishButton;
// console.log('Website loaded. englishButton:', englishButton);
var buttonList = document.getElementsByClassName("jw-reset");
for (var i = 0, len = buttonList.length; i < len; i++) {
if (buttonList[i].textContent === "English") {
englishButton = buttonList[i];
// console.log("englishButton found", englishButton);
break;
}
}
// console.log("End of window-load's callback. englishButton:", englishButton);
/*
Event Listener that detects when the shortcut key is hit.
When the shortcut Key is hit. It will simulate a mouse click on the subtitle button
*/
document.addEventListener("keyup", function(e) {
console.log(
"Inside document-keyup's callback. englishButton:",
englishButton
);
if (e.key == "z") {
//Logic to press the subitle button
console.log(
"Key matched: ",
e.key,
"Now click button. englishButton:",
englishButton
);
englishButton.click();
console.log("Shortcut Key");
} else {
console.log("Random Key");
}
});
englishButton.addEventListener("click", function() {
console.log("englishButton clicked!");
});
});
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button type="button" class="jw-reset">English</button>
</body>
</html>
But there are some things that could be improved in your code, so let's take a look at a more 'modernized' version of your code (comments in code):
// Using the `window` `load` event is fine, but
// you should prefer the `document` `DOMContentLoaded`
// event when possible, since it fires when the DOM
// has been constructed, while `load` means all assets have fully loaded (images).
// For your case since you are relying only on elements,
// `DOMContentLoaded` is a better choice.
document.addEventListener("DOMContentLoaded", function(event) {
/*
Looking for the subtitle button that states "English"
*/
var englishButton;
// Use `querySelectorAll` since it is more dynamic and
// will accept any type of selector. Also, for loops
// are avoided in most modern JavaScript because
// they create scoping and off-by-one errors.
// Since you want to break out of the loop here,
// we will use `.some()`. `Array.prototype.slice.call()`
// converts the NodeList returned by `querySelectorAll`
// into an Array.
Array.prototype.slice.call(document.querySelectorAll(".jw-reset")).some(
function (button) {
if (button.textContent === 'English') {
englishButton = button;
return true;
}
}
);
/*
Event Listener that detects when the shortcut key is hit.
When the shortcut Key is hit. It will simulate a mouse click on the subtitle button
*/
document.addEventListener("keyup", function(e) {
console.log(
"Inside document-keyup's callback. englishButton:",
englishButton
);
if (e.key === "z") {
//Logic to press the subitle button
console.log(
"Key matched: ",
e.key,
"Now click button. englishButton:",
englishButton
);
englishButton.click();
console.log("Shortcut Key");
} else {
console.log("Random Key");
}
});
englishButton.addEventListener("click", function() {
console.log("englishButton clicked!");
});
});
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button type="button" class="jw-reset">English</button>
</body>
</html>
IE appears not to always respond to a keyup event in one of my scripts.
I looked for an alternative way to detect if a key had been released.
Given that a held down key repeats the keydown event at intervals (except modifier keys on Mac), I thought it would be possible to increment a variable and listen for the point at which it stopped incrementing. When it stops incrementing, the key has been released?
Unfortunately, on occasions (not always), my script is detecting an end to the incrementing whilst the key is still held down. It tends to fail more if the key is held down for repeated short intervals. I have tested with IE and FF.
I have allowed for 2 seconds between checking each increment. Setting my Windows Control Panel to the slowest keyboard settings, 1 second would probably be sufficient.
<!DOCTYPE html>
<html>
<head>
<title>Detect keyup not using keyup event using Javascript</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
// opening variables
var keyDownCount = 0;
var nextLastTimeout1 = false;
var nextLastTimeout2 = false;
var lastCount = false;
var nextCount = false;
// function to compare the last two outcomes for keyDownCount by assigning them to variables lastCount and nextCount
function nextLastCount() {
if (lastCount) {
nextCount = keyDownCount;
if (lastCount === nextCount) {
// clear any outstanding timeouts
clearTimeout(nextLastTimeout1);
clearTimeout(nextLastTimeout2);
// they match, display the count in the html
document.getElementById('matched-next-last').innerHTML = keyDownCount;
} else {
// clear any outstanding timeouts
clearTimeout(nextLastTimeout1);
clearTimeout(nextLastTimeout2);
// reset variable
lastCount = false;
// they don't match, call the function again after allowing sufficient time for the key repetition rate to increment the keyDownCount
nextLastTimeout1 = self.setTimeout("nextLastCount()", 2000);
}
} else {
lastCount = keyDownCount;
if (lastCount === nextCount) {
// clear any outstanding timeouts
clearTimeout(nextLastTimeout1);
clearTimeout(nextLastTimeout2);
// they match, display the count in the html
document.getElementById('matched-next-last').innerHTML = keyDownCount;
} else {
// clear any outstanding timeouts
clearTimeout(nextLastTimeout1);
clearTimeout(nextLastTimeout2);
// reset variable
nextCount = false;
// they don't match, call the function again after allowing sufficient time for the key repetition rate to increment the keyDownCount
nextLastTimeout2 = self.setTimeout("nextLastCount", 2000);
}
}
}
// keydown listener
document.addEventListener('keydown', function(e) {
if (!e) e = window.event;
// listen for alt key down
if (e.altKey) {
if (keyDownCount === 0) {
// call nextLastCount() to start comparing the last two outcomes for keyDownCount
// allow sufficient time for the key repetition rate to increment keyDownCount
setTimeout("nextLastCount()", 2000);
}
// increment the counter on each keydown repeat
keyDownCount++;
// display the current count in the html
document.getElementById('display-count').innerHTML = keyDownCount;
}
});
// keyup listener
document.addEventListener('keyup', function(e) {
if (!e) e = window.event;
// listen for alt key released
if (!e.altKey) {
// clear any outstanding timeouts
clearTimeout(nextLastTimeout1);
clearTimeout(nextLastTimeout2);
// reset the counter and the html fields when the keys are released
keyDownCount = 0;
document.getElementById('display-count').innerHTML = keyDownCount;
document.getElementById('matched-next-last').innerHTML = "";
}
});
</script>
</head>
<body>
<p>Hold down the alt key to start the counter, relese to reset.</p>
<p>keyDownCount is: <span id="display-count"></span>
</p>
<p>Matching next and last detected on key count of: <span style="color:blue;" id="matched-next-last"></span>
</p>
</body>
</html>
In the unlikely event that someone else might need this, I resolved it as follows. Simplified code and only one timeout.
In Firefox, pressing the spacebar whilst the alt key is down will serve to simulate a non keyup event.
<!DOCTYPE html>
<html>
<head>
<title>Detect keyup without using keyup event</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
// opening variables
var keyDownCount = 0;
var nextLastTimeout = false;
var nextCount = false;
var lastCount = false;
var nextCountTime = false;
var lastCountTime = false;
// function to compare the last two outcomes for keyDownCount by assigning them to variables lastCount and nextCount
function nextLastCount() {
if (lastCount) {
nextCount = keyDownCount;
// record the time for use in calculating the keyboard delay
nextCountTime = +new Date(); // milliseconds since 01 January, 1970
if (lastCount === nextCount) {
// they match, display the count in the html
document.getElementById('matched-next-last').innerHTML = keyDownCount;
}else{
// reset variable
lastCount = false;
}
}else{
lastCount = keyDownCount;
// record the time for use in calculating the keyboard delay
lastCountTime = +new Date(); // milliseconds since 01 January, 1970
if (lastCount === nextCount) {
// they match, display the count in the html
document.getElementById('matched-next-last').innerHTML = keyDownCount;
}else{
// reset variable
nextCount = false;
}
}
}
// keydown listener
document.addEventListener('keydown',function(e) {
if(!e) e = window.event;
// listen for alt key down
if (e.altKey) {
// increment the counter on each keydown repeat
keyDownCount++;
// display the current count in the html
document.getElementById('display-count').innerHTML = keyDownCount;
// see below
clearTimeout(nextLastTimeout);
// call function
nextLastCount();
// calculate the keyboard delay i.e. time between repeated keystrokes
if (nextCountTime && lastCountTime) {
// returns an always positive value in milliseconds
var keyboardDelay = Math.abs(nextCountTime - lastCountTime);
}else{
// in the first few increments both count times are not available, use an estimate
var keyboardDelay = 3000; // also 500ms added below
}
// call nextLastCount() again, but on a delay that exceeds the keyboard delay
// .. for safety, add 500ms to the calculated / estimated keyboard delay
// this timeout will only complete when the increments stop
// .. see clearTimeout(nextLastStickyTimeout) above
nextLastTimeout = setTimeout("nextLastCount()",keyboardDelay + 500);
}
});
// keyup listener
document.addEventListener('keyup',function(e) {
if(!e) e = window.event;
// listen for alt key released
if (!e.altKey) {
// clear any outstanding timeouts
clearTimeout(nextLastTimeout);
// reset the counter and the html fields when the keys are released
keyDownCount = 0;
document.getElementById('display-count').innerHTML = keyDownCount;
document.getElementById('matched-next-last').innerHTML = "";
}
});
</script>
</head>
<body>
<p>Hold down the alt key to start the counter, release to reset.</p>
<p>In Firefox, pressing the spacebar whilst the alt key is down will simulate a non keyup event</p>
<p>keyDownCount is: <span id="display-count"></span></p>
<p>Matching next and last detected on key count of: <span style="color:blue;"id="matched-next-last"></span></p>
</body>
</html>
This seems like something that should have already been solved. Here is a SO question on the best input libraries out there: which is the best Javascript Keyboard event library.(Hotkeys,Shortcuts )
Ideally you don't want to reinvent the wheel.
Using JavaScript how do you to detect what text the user pastes into a textarea?
You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: How to get the start and end points of selection in text area?
function getTextAreaSelection(textarea) {
var start = textarea.selectionStart, end = textarea.selectionEnd;
return {
start: start,
end: end,
length: end - start,
text: textarea.value.slice(start, end)
};
}
function detectPaste(textarea, callback) {
textarea.onpaste = function() {
var sel = getTextAreaSelection(textarea);
var initialLength = textarea.value.length;
window.setTimeout(function() {
var val = textarea.value;
var pastedTextLength = val.length - (initialLength - sel.length);
var end = sel.start + pastedTextLength;
callback({
start: sel.start,
end: end,
length: pastedTextLength,
text: val.slice(sel.start, end)
});
}, 1);
};
}
var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
alert(pasteInfo.text);
// pasteInfo also has properties for the start and end character
// index and length of the pasted text
});
HTML5 already provides onpaste not only <input/> , but also editable elements (<p contenteditable="true" />, ...)
<input type="text" onpaste="myFunction()" value="Paste something in here">
More info here
Quite an old thread, but you might now use https://willemmulder.github.io/FilteredPaste.js/ instead. It will let you control what gets pasted into a textarea or contenteditable.
Works on IE 8 - 10
Creating custom code to enable the Paste command requires several steps.
Set the event object returnValue to false in the onbeforepaste event to enable the Paste shortcut menu item.
Cancel the default behavior of the client by setting the event object returnValue to false in the onpaste event handler. This applies only to objects, such as the text box, that have a default behavior defined for them.
Specify a data format in which to paste the selection through the getData method of the clipboardData object.
invoke the method in the onpaste event to execute custom paste code.
To invoke this event, do one of the following:
Right-click to display the shortcut menu and select Paste.
Or press CTRL+V.
Examples
<HEAD>
<SCRIPT>
var sNewString = "new content associated with this object";
var sSave = "";
// Selects the text that is to be cut.
function fnLoad() {
var r = document.body.createTextRange();
r.findText(oSource.innerText);
r.select();
}
// Stores the text of the SPAN in a variable that is set
// to an empty string in the variable declaration above.
function fnBeforeCut() {
sSave = oSource.innerText;
event.returnValue = false;
}
// Associates the variable sNewString with the text being cut.
function fnCut() {
window.clipboardData.setData("Text", sNewString);
}
function fnBeforePaste() {
event.returnValue = false;
}
// The second parameter set in getData causes sNewString
// to be pasted into the text input. Passing no second
// parameter causes the SPAN text to be pasted instead.
function fnPaste() {
event.returnValue = false;
oTarget.value = window.clipboardData.getData("Text", sNewString);
}
</SCRIPT>
</HEAD>
<BODY onload="fnLoad()">
<SPAN ID="oSource"
onbeforecut="fnBeforeCut()"
oncut="fnCut()">Cut this Text</SPAN>
<INPUT ID="oTarget" TYPE="text" VALUE="Paste the Text Here"
onbeforepaste="fnBeforePaste()"
onpaste="fnPaste()">
</BODY>
Full doc: http://msdn.microsoft.com/en-us/library/ie/ms536955(v=vs.85).aspx
I like the suggestion for the right click
$("#message").on('keyup contextmenu input', function(event) {
alert("ok");
});
finded here:
Source:
Fire event with right mouse click and Paste
Following may help you
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == //event code of ctrl-v)
{
//some code here
}
}
<teaxtarea name="area[name]" onKeyPress=>"return submitenter(this,event);"></textarea>
The input event fires when the value of an , , or element has been changed.
const element = document.getElementById("input_element_id");
element.addEventListener('input', e => {
// insertText or insertFromPaste
if(inputType === "insertFromPaste"){
console.log("This text is copied");
}
if(inputType === "insertText"){
console.log("This text is typed");
}
})
You could either use html5 oninput attribute or jquery input event
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$("body").on('input','#myinp',function(){
$("span").css("display", "inline").fadeOut(2000);
});
</script>
<style>
span {
display: none;
}
</style>
</head>
<body>
<input id="myinp" type="search" onclick="this.select()" autocomplete="off" placeholder="paste here">
<span>Nice to meet you!</span>
</body>
</html>
How do you catch the client-side event when a browser changes an input text field using the browser's autocomplete feature for a plain HTML input field? (This is the small dropdown on input fields that is supplied by the browser, I know that you can disable it with "autocomplete=off" in some browsers per input field.)
I'm already binding to the "change/keyup" event, but these don't handle the case when the user starts typing in a value and uses the Browser's native autocomplete to fill in the rest of the field (and staying in the focus of the field.)
The only foolproof way I know of to always catch ALL changes no matter how they're done is to use a setInterval. This is somewhat CPU intensive, though, so you probably want to try to keep the selector more minimal than this.
setInterval( function() {
$('input').each( function() {
if ($(this).val() != $(this).attr("_value")) {
// Save the new value
$(this).attr("_value", $(this).val());
// TODO - Handle the changed value
}
});
}, 100);
I'm surprised that the 'change' event doesn't fire to be honest...
Anyway, Plutor has the right idea. A more CPU friendly version of his answer:
var value,
elem = $('input[name=email]')[0];
setInterval(function(){
if (elem.value !== value) { /* do something */ }
value = elem.value;
}, 100);
you can call your function in your function for next time after many seconds , try this :
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head></head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
reference is : http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock