Prevent function onkeydown javascript - javascript

Hello I'm new to this and I have a script that will fire function on keydown. But I also have an input text field box and if I'm typing in that input field box and press the key to that fires the function. The function fires but I don't want the function to fire if I'm typing in the input field would there be a way to do this?
window.addEventListener("onkeydown", keyDown, true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 72: // Key H
test();
break;
}
}
function test() {
document.getElementById('Codefield').value = Math.random().toString(36).substring(2, 15);
}
<input id="Codefield" value="" type="text">
<input id="Codefield2" value="Stop test function keydown or keydown if typeing here" type="text">

If you add event listeners to window, all your inputs will fire the function. Add the event listener only where you need it.
document.getElementById('Codefield').addEventListener("onkeydown", keyDown, true);
Another technique would be to check the e.target from inside the trigger function and ignore the code if it is from an input you don't want to handle.

You can check whether the current element is an input element.
function keyDown(e) {
if (this.tagName == 'INPUT') {
e.stopPropagation();
return;
}
switch (e.keyCode) {
case 72: // Key H
test();
break;
}
}
Also, don't use window.event. That's non-standard and won't work in Firefox. The event is the first argument to the event listener.

Maybe you should use a focus selector (from jQuery):
if($("#Codefield2:focus")) {
thisInput = true;
}
Then add an if statement at the start of your function, and check if thisInput is true or not.

Related

How to trigger a button click on key press

<input type = “reset” onclick=‘outputx()’>
I want to trigger the button without me clicking on it when the d key is pressed. Output the function and reset at the same time.
You add an event listener to the window. The ASCII code for the letter d is 68.
window.addEventListener("keydown", onKeyDown, true);
function onKeyDown(e){
if(e.keyCode == 68){
outputx();
}
}
First, you have smart quotes “” instead of straight quotes (""). Never use formatted text when coding.
Next, just set up a keydown event handler on the document that checks to see if the d key was pressed:
function output(){
console.log("You did it!");
}
document.addEventListener("keydown", function(event){
if(event.key === "d"){
document.querySelector("input[type='reset']").click();
}
});
<input type = "reset" onclick="output()">

stop function from running if user types in the input

Hi i know this is probably a silly question but i only started to learn javascript today but i was wondering if someone could help me or point me in the right direction
i'm wondering how can i stop a function from running that fires on keydown when a user is typing in the input
javascript
window.addEventListener("onkeydown", keyDown, true);
window.addEventListener("keydown", keyDown);
function keyDown(e) {
switch (e.keyCode) {
case 86: // Key V = myFunction
myFunction();
break;
}
}
function myFunction() {
// do something
console.log("oh no the function fired why typing in the input!")
}
input
<input type="text" name="message" class="chat-input" placeholder="Enter your chat message..." maxlength="140">
I think this is not about exiting a function... seems user asks about avoiding to run a event associated to the window onkey event if focus is on an input form element.
For this to work you cannot declare window.addEventListener("onkeydown", keyDown, true) with true, because this will associate keyDown function to the capturing event handling sequence. You need to associate to the bubbling so use instead false in the last argument.
window.addEventListener("keydown", keyDown, false);
Then in the input associate an dummy event handler and stop the propagation of the event, like this:
var inputObj = document.querySelector(".chat-input");
inputObj.addEventListener("keydown", function(e) {
e.stopPropagation();
}, false);
By doing this if browser focus is on the input element the inputObj event handler will be triggered before the window handler and by stopping the propagation the event will not be propagated to the window handler so keyDown function will not receive the event.
Other way to do this is to check the e.target property which contains the element focused when the event was triggered and discard the event if needed.
Check for example What is event bubbling and capturing? for more info.
Create a boolean value & use it in the function
let canExecute = true;
window.addEventListener("onkeydown", keyDown, true);
window.addEventListener("keydown", keyDown);
function keyDown(e) {
switch (e.keyCode) {
case 86: // Key V = myFunction
myFunction();
break;
}
}
function myFunction() {
if (canExecute) {
// this will only execute once
// do something
console.log("oh no the function fired why typing in the input!")
}
canExecute = false;
}
<input type="text" name="message" class="chat-input" placeholder="Enter your chat message..." >

Catching TAB key press with keyup

I need to archieve 2 objectives but I archive one at time, never both of them.
First I have an input field that should fires an event when a key is pressed and I need to catch the field value. I use letters, number and the TAB key. So if I use keyup it fires at the first char. If I use keydown it takes 2 char to fire because when it fires the first time the char is not pressed yet. So when I press for the second time it fires with the first letter and so on.
Said that, it is clear that what I need is the keyup event that put the value in the field then the event is fired. But TAB has a special meaning in my case and it is not the default behavior and with TAB key I am unable to catch e.which, e.charCode nor e.keyCode! Only with keydown I am able to get those value!
Now I don´t have a clue what to do. How could I catch TAB key or make keydown catch the value of a field?
P.S keypress also working as keydown. Event is fired before I have the value in the field
EDIT 1:
Here is the code:
$('input[data-action="keyupNome"]').each(function () {
$(this).on("keypress", function(e) {
//Se o campo não estiver vazio
if($(this).val() != '') {
if(key != 9) // the tab key code
{
limpaCamposBusca('nome');
var width = $('#nomeBusca').width();
$('.nomeContainer').css('width', width);
$('.displayNomeTbl').css('width', width);
buscaEndereco('Controller/Dispatcher.php?classe=Buscas&acao=buscaEnderecoPorNome', 'nome');
}//if key == 9
else {
alert('here');
e.preventDefault();
}
}// val == ''
else {
clearFields();
clearBuscaCliente();
reactivateFields();
}
});
});
The trick is to use keydown and to combine actual value of the field with the char currently pressed OR to catch TAB in keydown and set an external variable to be used in keyup as in my example.
EDIT :
In fact, I realized that not preventing default behavior of TAB in keydown doesn't fire keyup. So, no variable is needed, but only preventing TAB on keydown. Anyhow, this version always work if the glitch you talked about exist in some circumstances.
(function() {
var tabKeyPressed = false;
$("#t").keydown(function(e) {
tabKeyPressed = e.keyCode == 9;
if (tabKeyPressed) {
e.preventDefault();
return;
}
});
$("#t").keyup(function(e) {
if (tabKeyPressed) {
$(this).val("TAB"); // Do stuff for TAB
e.preventDefault();
return;
}
//Do other stuff when not TAB
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="t" value="">

jQuery trigger keyup on input gets old value

I try to manually trigger key-up event in qunit test but it fails since manually trigger key-up event will not change the input value.
http://jsfiddle.net/Re9bj/4/
$('input').on('keyup', function (event) {
$('div').html($('input').val());
});
var e = $.Event('keyup', {
keycode: 68
});
$('input').trigger(e); //this trigger will not change the input value
This trigger will work but the problem is that input value never change.
You can't add a character with a simple trigger. Trigger will only fire events, but not the default behavior. You need to simulate it.
To do that, you can use this code :
if(event.isTrigger && event.keycode) this.value += String.fromCharCode(event.keycode);
It will check if the event is triggered and then print the value.
Final code :
$('input').on('keyup', function (event) {
if(event.isTrigger && event.keycode) this.value += String.fromCharCode(event.keycode);
$('div').html($('input').val());
});
var e = $.Event('keyup', {
keycode: 68
});
$('input').trigger(e);
Fiddle : http://jsfiddle.net/Re9bj/9/

Trigger a keypress/keydown/keyup event in JS/jQuery?

What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?
I don't want to actually put text in the input box, I just want to trigger all the event handlers that would normally get triggered by a user typing info into a input box. This means focus, keydown, keypress, keyup, and blur. I think.
So how would one accomplish this?
You can trigger any of the events with a direct call to them, like this:
$(function() {
$('item').keydown();
$('item').keypress();
$('item').keyup();
$('item').blur();
});
Does that do what you're trying to do?
You should probably also trigger .focus() and potentially .change()
If you want to trigger the key-events with specific keys, you can do so like this:
$(function() {
var e = $.Event('keypress');
e.which = 65; // Character 'A'
$('item').trigger(e);
});
There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.
You could dispatching events like
el.dispatchEvent(new Event('focus'));
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
To trigger an enter keypress, I had to modify #ebynum response, specifically, using the keyCode property.
e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);
Here's a vanilla js example to trigger any event:
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
You can achieve this with: EventTarget.dispatchEvent(event) and by passing in a new KeyboardEvent as the event.
For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))
Working example:
// get the element in question
const input = document.getElementsByTagName("input")[0];
// focus on the input element
input.focus();
// add event listeners to the input element
input.addEventListener('keypress', (event) => {
console.log("You have pressed key: ", event.key);
});
input.addEventListener('keydown', (event) => {
console.log(`key: ${event.key} has been pressed down`);
});
input.addEventListener('keyup', (event) => {
console.log(`key: ${event.key} has been released`);
});
// dispatch keyboard events
input.dispatchEvent(new KeyboardEvent('keypress', {'key':'h'}));
input.dispatchEvent(new KeyboardEvent('keydown', {'key':'e'}));
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
<input type="text" placeholder="foo" />
MDN dispatchEvent
MDN KeyboardEvent
You're now able to do:
var e = $.Event("keydown", {keyCode: 64});
First of all, I need to say that sample from Sionnach733 worked flawlessly. Some users complain about absent of actual examples. Here is my two cents. I've been working on mouse click simulation when using this site: https://www.youtube.com/tv. You can open any video and try run this code. It performs switch to next video.
function triggerEvent(el, type, keyCode) {
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.keyCode = keyCode;
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.keyCode = keyCode;
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
var nextButton = document.getElementsByClassName('icon-player-next')[0];
triggerEvent(nextButton, 'keyup', 13); // simulate mouse/enter key press
For typescript cast to KeyboardEventInit and provide the correct keyCode integer
const event = new KeyboardEvent("keydown", {
keyCode: 38,
} as KeyboardEventInit);
I thought I would draw your attention that in the specific context where a listener was defined within a jQuery plugin, then the only thing that successfully simulated the keypress event for me, eventually caught by that listener, was to use setTimeout().
e.g.
setTimeout(function() { $("#txtName").keypress() } , 1000);
Any use of $("#txtName").keypress() was ignored, although placed at the end of the .ready() function. No particular DOM supplement was being created asynchronously anyway.

Categories