I made a cookie clicker using javascript and html, and at the moment I have it made so that upon clicking an image, it fires a function which increases your score. I want to make it so that instead of only being able to click the image, you can just click any button on the keyboard to fire the same function. I've only seen code to do this in an input field. I'm not sure if "document.addEventListener("keydown", function())" is what I'm looking for.
Try:
document.onkeydown = function() {
console.log('my code');
};
Edit (or):
document.onkeydown = myFn;
To listen for keypress you can add keydown event on document
document.addEventListener("keydown", callBack, false);
function callBack(e) {
var keyCode = e.keyCode;
console.log(keyCode);
}
Just assign a event handler to your event.
If you want to assign for the whole document, use this:
document.addEventListener("keydown", keyDownTextField, false);
document.getElementById("yourinput").addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
console.log(e.keyCode);
}
<input id="yourinput" type="text" />
document.addEventListener('keydown', () => {
console.log('a');
});
should work.
However, some browsers don't give document focus, which is required for keydown events.
The classic approach to this (which works more universally) is to create an off-screen <input> element, and give it a blur event to regain focus when it loses it. This will force focus to always stay on that input, then it can receive key events.
const input = document.createElement('input');
input.style.position = 'absolute';
input.style.left = '-100000px';
input.addEventListener('blur', () => input.focus());
input.addEventListener('keydown', () => console.log('key down'));
document.body.appendChild(input);
input.focus();
This code:
- creates a new input element
- positions it absolutely way off the left of the screen (so it's not visible)
- adds a blur event which automatically gets focus back
- adds the keydown event itself
Related
I need to simulate a user input in an input field:
<input type="text" id="name">
The following events should get triggered manually:
mousedown > focus > mouseup > click > keydown > keypress > change >
blur
Code show here
If I use this code, they should get detected:
var element = document.getElementById('name');
$(element).on('mousedown focus mouseup click keydown keypress change blur', function(e){
console.log(e);
});
Updated file (doesn't get detected, no console logs..):
$("#name").trigger("mousedown");
$("#name").trigger("focus");
$("#name").trigger("mouseup");
$("#name").trigger("click");
$("#name").trigger("keydown");
$("#name").trigger("keypress");
$("#name").trigger("change");
$("#name").trigger("blur");
var element = document.getElementById('name');
$(element).on('mousedown focus mouseup click keydown keypress change blur', function(e){
console.log(e);
});
You would use jQuery's trigger for this. So, if you wanted to simulate the events in the order you described:
$("#name").trigger("mousedown");
$("#name").trigger("focus");
$("#name").trigger("mouseup");
$("#name").trigger("click");
$("#name").trigger("keydown");
$("#name").trigger("keypress");
$("#name").trigger("change");
$("#name").trigger("blur");
If you want to really similuate a user, you could use some setTimeout to simulate human delay as well. Good luck!
Try This --
Add Jquery plugin
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" id="name">
//var element = document.getElementById('name');
$("input").trigger("mousedown");
$("input").trigger("focus");
$("input").trigger("mouseup");
$("input").trigger("click");
$("input").trigger("keydown");
$("input").trigger("keypress");
$("input").trigger("change");
$("input").trigger("blur");
You can use the trigger jquery function to simulate and trigger any events.
I have one callback function bound to two events (change and focusout). However, I need the focusout to happen only when the element we're interacting with is not a checkbox.
This is the example code:
$(document).on('focusout change', '.selector', function() {
if ($(this).is(':checkbox')) {
// Do stuff and prevent the focusout to trigger. HOW???
}
doStuff(); // Action that applies to both cases, but needs to be limited at one execution only
});
The code above will execute twice:
When the checkbox gets checked/unchecked
When you click outside of the checkbox (lose focus (blur))
I tried using .off, but it ends up killing the focousout handler altogether, which I will need later for other elements which aren't checkboxes.
What would be the way to prevent the focusout handler to trigger for certain elements?
What you want to do is
$(document).on('focusout change', '.selector', function(event) {
event is an event object, which has properties, one of which is type. Checking the type you can now see if your function has been called because of a focusout or a change and run code as appropriate
The best way is to affect both events (or more) to the same function, like this :
A text input for example
<input id="myfield" type="text" />
Now the Javascript
var myfield = document.getElementById('myfield');
myfield.onfocus = myfield.onchange = function(e)
{
//your code
}
Yo can even add an other element
button.onclick = myfield.onkeyup = function(e)
{
//when the client press the enter key
if(e.key && e.key == "Enter")
{
//catch the target
}
//when the client click the button
else if(!e.key || e.target == button)
{
//catch the target
}
//otherwise you can do not care about the target and just execute your function
}
You must only know that you can add many elements and many events
element1.onfocus = element1.onblur = element2.onchange = element3.onchange = function(e){//your code}
I want to change input type text to password. But it doesn't work in ie8. I found a solution; clone and replace input but onblur doesn't work after clone.
The debugger doesn't break OnBlur function. Can somebody show me?
Here is js code :
$(document).ready(function () {
var input = document.getElementById("Password");
var input2 = input.cloneNode(false);
input2.id = 'password1';
input2.type = 'password';
$('#Password').focus(function () {
input.parentNode.replaceChild(input2, input);
input2.focus();
});
$('#password1').blur(function () {
if ($(this).val() == '' || $(this).val() == Passwordtxt) {
document.getElementById("password1").setAttribute("type", "text");
$(this).val(Passwordtxt);
}
});
});
Change
$('#password1').blur(function () {
to
$('body').on('focusout','#password1',function () {
See .on()
The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble. When focus and blur are used to attach delegated event handlers, jQuery maps the names and delivers them as focusin and focusout respectively. For consistency and clarity, use the bubbling event type names.
use on event delegate
try this
$(document).on('blur','#password1',function () {...
replacing the document with the closest element is preffered
Anyone know how to prevent an HTML checkbox from getting focus when clicked? I still want it to change state, just not get focus.
You can prevent the focus by using preventDefault() in a mousedown handler:
$('input[type=checkbox]').mousedown(function (event) {
// Toggle checkstate logic
event.preventDefault(); // this would stop mousedown from continuing and would not focus
});
In pure JavaScript:
checkbox.onmousedown = function (event) {
// Toggle checkstate logic
event.preventDefault(); // this would stop mousedown from continuing and would not focus
}
Give this CSS:
input {outline: 0;}
But be aware that when you move control using Tab key, it won't be possible to identify which control are you in currently.
Update #1
Use this JavaScript:
$('input[type=checkbox]').click(function () {
this.blur();
});
I've got a simple Listbox on a HTML form and this very basic jQuery code
//Toggle visibility of selected item
$("#selCategory").change(function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
});
The change event fires fine when the current item is selected using the Mouse, but when I scroll through the items using the keyboard the event is not fired and my code never executes.
Is there a reason for this behavior? And what's the workaround?
The onchange event isn't generally fired until the element loses focus. You'll also want to use onkeypress. Maybe something like:
var changeHandler = function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
}
$("#selCategory").change(changeHandler).keypress(changeHandler);
You'll want both onchange and onkeypress to account for both mouse and keyboard interaction respectively.
Sometimes the change behavior can differ per browser, as a workaround you could do something like this:
//Toggle visibility of selected item
$("#selCategory").change(function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
}).keypress(function() { $(this).change(); });
You can chain whatever events you want and manually fire the change event.
IE:
var changeMethod = function() { $(this).change(); };
....keypress(changeMethod).click(changeMethod).xxx(changeMethod);
The behavior you describe, the change event triggering by keyboard scrolling in a select element, is actually an Internet Explorer bug. The DOM Level 2 Event specification defines the change event as this:
The change event occurs when a control
loses the input focus and its value
has been modified since gaining focus.
This event is valid for INPUT, SELECT,
and TEXTAREA. element.
If you really want this behavior, I think you should look at keyboard events.
$("#selCategory").keypress(function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 38 || keyCode == 40) { // if up or down key is pressed
$(this).change(); // trigger the change event
}
});
Check a example here...
I had this problem with IE under JQuery 1.4.1 - change events on combo boxes were not firing if the keyboard was used to make the change.
Seems to have been fixed in JQuery 1.4.2.
$('#item').live('change keypress', function() { /* code */ });