Native callback previous value of text input using JavaScript? - javascript

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>

Related

JS - How to disable spacebar scrolling ONLY, but allow other spacebar functionality?

I have a website which has regular spacebar functionality, not just inside an input box, so I can't make it return false if the target is the body. I just want to stop it from scrolling down the page, but allow the other functionality. Is it possible to do this using vanilla JS? Here is my code:
//Many other functions here
function spacebar() {
window.onkeydown = function(e) {
if ((watch.isOn) && (!done)) {//u can stop it with any key
watch.freeze();//stop the stopwatch
}
else if (e.keyCode == 32) {
if (done) {
watch.start();//start the stopwatch
stage = 1;
}
if (stage === 0) {
stage = 1;
}
}
}
<html>
<body>
<h1 id="timer">0:00.000</h1>
<script src="js/timer.js"></script>
<!--The JS starts and stops this timer.-->
</body>
</html>
So it starts the timer when the spacebar is pressed, and stops it when any key is pressed.
A default behaviour of pressing the spacebar is to scroll. We have the ability to prevent default behaviors using
event.preventDefault();
You are using window.onkeydown, passing the event argument as var e. You know how to recognize keys by keycode, as you have demonstrated. Now then, if the key that is pressed is the spacebar, then prevent the default behaviors (in this case that includes scrolling). You have the option to define your own behavior instead.
What you can do is that You can add e.preventDefault(); with your functionality like as i can play and pause the song but restrict the Scrolling.
$(window).keypress(function(e) {
if (e.which == 32) {
const isMusicPaused = wrapper.classList.contains("paused");
isMusicPaused ? pausedMusic() : playMusic();
e.preventDefault();
}});

Detect key released without using keyup event - Javascript

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 a function on textbox focus?

I want to add a autocomplete function to a site and found this guide which uses some js code which works really nice for one textbox: http://www.sks.com.np/article/9/ajax-autocomplete-using-php-mysql.html
However when trying to add multiple autocompletes only the last tetbox will work since it is the last one set.
Here is the function that sets the variables for the js script
function setAutoComplete(field_id, results_id, get_url)
{
// initialize vars
acSearchId = "#" + field_id;
acResultsId = "#" + results_id;
acURL = get_url;
// create the results div
$("#auto").append('<div id="' + results_id + '"></div>');
// register mostly used vars
acSearchField = $(acSearchId);
acResultsDiv = $(acResultsId);
// reposition div
repositionResultsDiv();
// on blur listener
acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });
// on key up listener
acSearchField.keyup(function (e) {
// get keyCode (window.event is for IE)
var keyCode = e.keyCode || window.event.keyCode;
var lastVal = acSearchField.val();
// check an treat up and down arrows
if(updownArrow(keyCode)){
return;
}
// check for an ENTER or ESC
if(keyCode == 13 || keyCode == 27){
clearAutoComplete();
return;
}
// if is text, call with delay
setTimeout(function () {autoComplete(lastVal)}, acDelay);
});
}
For one textbox I can call the function like this
$(function(){
setAutoComplete("field", "fieldSuggest", "/functions/autocomplete.php?part=");
});
However when using multiple textboxes I am unsure how I should go about doing this, here is something I did try but it did not work
$('#f1').focus(function (e) {
setAutoComplete("f1", "fSuggest1", "/functions/autocomplete.php?q1=");
}
$('#f2').focus(function (e) {
setAutoComplete("f2", "fSuggest2", "/functions/autocomplete.php?q2=");
}
Thanks for your help.
You should be using classes to make your function work in more than one element on the same page. Just drop the fixed ID's and do a forEach to target every single element with that class.

how to add dbclick() on right click in jquery

Hi I want to have a dblclick() on the right click as the google maps have to zoom in and zoom out. Is there any way to do that. I have written the dblclick but now its working with only left click. Any pointers on how to do this. Here is my code
$("div#demo1").dblclick(function(e) {
//alert(e.getElementById());
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
alert("Left Mouse Button was clicked on demo1 div!");
$("div.window").animate({
'height':'+=20', 'width':'+=20'
},0,function(){
jsPlumb.repaintEverything();
jsPlumb.repaintEverything();
});
// Left mouse button was clicked (all browsers)
}
else if( (!$.browser.msie && e.button == 2) || ($.browser.msie && e.button == 3) ) {
alert("right click double");
}
});
There is another way you could detect a double right-click that does not involve fiddling with timers or keeping track of click counts manually. Using the .detail property of the event object in a mouseup or mousedown event. .detail holds the click count which will tell you how many clicks have happened recently. If .detail === 2 it was a double-click.
// suppress the right-click menu
$('#target').on('contextmenu', function (evt) {
evt.preventDefault();
});
$('#target').mouseup(function (evt) {
if (evt.which === 3) { // right-click
/* if you wanted to be less strict about what
counts as a double click you could use
evt.originalEvent.detail > 1 instead */
if (evt.originalEvent.detail === 2) {
$(this).text('Double right-click');
} else if (evt.originalEvent.detail === 1) {
$(this).text('Single right-click');
}
}
});
You might notice that I am using evt.originalEvent.detail to access the property instead of just .detail. This is because jQuery provides it's own version of the event object which does not include .detail, but you can access the original event object that the browser returned via .originalEvent. If you were using pure JavaScript instead of jQuery you would just use evt.detail.
Here's a working example.
There is no real way to do it, you can emulate it by taking the default timer for double clicks which IIRC is 300ms:
function makeDoubleRightClickHandler( handler ) {
var timeout = 0, clicked = false;
return function(e) {
e.preventDefault();
if( clicked ) {
clearTimeout(timeout);
clicked = false;
return handler.apply( this, arguments );
}
else {
clicked = true;
timeout = setTimeout( function() {
clicked = false;
}, 300 );
}
};
}
$(document).contextmenu( makeDoubleRightClickHandler( function(e) {
console.log("double right click" );
}));
http://jsfiddle.net/5kvFG/2/
Because the right-click has meaning to the user agent that is outside the purview of javascript (the context menu), you're going to have to do some dancing around.
First, you should disable the context menu on the target element:
document.getElementById('demo1').oncontextmenu = function() {
return false;
};
Now, when we right click, there won't be the context menu messing up the second click.
Next, understand that "double-click right" does not, generally speaking, exist. Even though you can bind the dblclick event, that isn't a generic event. "Double-click" is, by definition, double-clicking with the left mouse button.
So, we'll have to use the mousedown event, check to see how many times the right has been clicked, and react after two. I created a small helper function that keeps track of the click count and resets the state after a short time-frame.
var RightClick = {
'sensitivity':350,
'count':0,
'timer':false,
'active':function () {
this.count++;
this.timer = setTimeout(
this.endCountdown.bind(this),
this.sensitivity
);
},
'endCountdown': function () {
this.count = 0;
this.timer = false;
}
};
$("div#demo1").mousedown(function(e) {
if(e.which == 3) {
RightClick.active();
if (RightClick.count == 2)
alert("right click double");
}
});
Try it here: http://jsfiddle.net/94L7z/
You can adjust the sensitivity rate, allowing for shorter or longer double-clicks, depending on your preference.
Documentation
element.onContextMenu on MDN - https://developer.mozilla.org/en-US/docs/DOM/window.oncontextmenu
element.onMouseDown on MDN - https://developer.mozilla.org/en-US/docs/DOM/element.onmousedown
window.setTimeout on MDN - https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout
jQuery event.which - http://api.jquery.com/event.which/
"Javascript Madness: Mouse Events" on UnixPapa.com, an article showing some tests related to mouse events and the left/right buttons - http://unixpapa.com/js/mouse.html
The problem is the concept of double clicking is only relevant to the left mouse button as far as JS is concerned. So no matter how many time, and how fast you click the right mouse button, it just registers as a bunch of single clicks. So what to do?
Create a global variable to track click count
detect a single right-click, you already know how to do this it seems
set the global variable that the right-click was fired once
set a timeout, so if another right click doesn't come through in a
reasonable time to be considered a dblclick the global variable
resets to 0. I recommend 300 ms, it seems to be the most natural
each time a right-click registers check that variable, if it's more
than one, fire your double-right-click handler.
you may want to make that global variable an object so you can track which element
registered the right click and expire specific element right clicks
accordingly. This will allow you to ignore if they double click
while moving the mouse over various objects. I consider this
optional as the chain of events are unlikely for a user to follow,
but depending on your app may result in unexpected functionality.
It might be better to define a jQuery function with this (try it):
var precision = 400;
var lastClickTime = 0;
$(document).ready(function()
{
var div = $('#div');
$(div).bind("contextmenu", function(e)
{
return false;
});
$(div).mousedown(function(event)
{
if (event.which == 3)
{
var time = new Date().getTime();
if(time - lastClickTime <= precision)
{
// DOUBLE RIGHT CLICK
alert('double click');
}
lastClickTime = time;
}
});
});

Detect pasted text with Ctrl+v or right click -> paste

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>

Categories