I need to have a start and stop event on input range, so I can detect when dragging start and when it ends. Are these good events to use or is there a better way?
var input = document.getElementById('input')
input.addEventListener("mousedown", function() {
console.log('start')
}, false);
input.addEventListener("change", function() {
console.log('end')
}, false);
<input id="input" type="range" min="0" max="100" value="" />
I suggest using mousedown and/or mouseup too because the user can click anywhere in this range, and don't have to drag it necessary.
These events seem fine, but try just clicking on the input without dragging it. The console only logs "start" if you don't change the value.
If you want to capture that, you can just use the "mouseup" event.
input.addEventListener("mouseup", function-here);
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 am creating a browser game and i have keys set which moves the player around.
Let's get a weird example to help understand the problem.
Space bar - Jump
So when i go to the chatbox, and start typing the player jumps every time you press the space bar like it is intended to. However, when i am typing in a input field, it should not jump the player for pressing the space bar.
This is the input field:
<textarea id="chatfield1" class="pull-left" placeholder="Participate in coversation"></textarea>
I have a keymanager that enables and disables the ability to execute functions with keys.
keymanager.suspend();
keymanager.resume();
How could i do this?
edit:
My keymanager works like this:
var keymanager = {
"active": true,
"suspend": () => {
keymanager.active = false;
},
"resume": () => {
keymanager.active = true;
}
};
document.body.onkeyup = function(e){
if (!keymanager.active)
{
return; // do not process any keys
}
That's because the event bubbles from child-to-parent.
document.body is the parent to almost every element on your page, including your input/textarea.
You have (at least) 2 options:
Listen for the keyup on a non-parent element of your input/textarea. For example, if this is an HTML5 canvas game you should probably listen for game-related key events on the <canvas> itself.
Stop the keyup event propagation when you type in the input/textarea.
Here's the second example in action:
document.querySelector('#parent').addEventListener('keyup', () => {
// this shouldn't run since we stop the event propagation below.
console.log('keyup detected on parent')
})
document.querySelector('#input').addEventListener('keyup', e => {
console.log('keyup detected on input')
e.stopPropagation()
})
<div id="parent">
<input id="input" placeholder="Type here..." value=""/>
</div>
That being said, you should probably go for the 1st option instead. Explicitly stopping event propagation every time some secondary input is required will soon become unwieldy.
To move focus on the end of inputs when user click the input box,
I use something like this,
$(function() {
$('#test-input').on('click', function(evt) {
$target = $(evt.target);
var val = $target.val();
$target.val('').val(val);
});
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="test" id="test-input" value="abcdefgh" />
But if I change the 'click' to 'focus', it doesn't work.
$(function() {
$('#test-input').on('focus', function(evt) {
$target = $(evt.target);
var val = $target.val();
$target.val('').val(val);
});
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="test" id="test-input" value="abcdefgh" />
How different onClick and onFocus actions in that case?
There's some differences:
onClick: This event is fired whenever the user clicks in an object, like a button, an image, an input... After the click, then comes the:
onFocus: This event is fired when an element is selected, it doesn't need to be clicked, it can be done programmatically, calling .focus() or using the Tab key, for example. Also, using onfocus instead of onclick, can help to avoid bubbling.
To finish, use the snippet below (I added more inputs, cycle through it with TAB (or click too), you'll see the caret going to end on all of then.
Why I added a timeout?
Chrome Browser has an odd quirk where the focus event fires before the cursor is moved into the field, so, the event must wait to the cursor to get there before moving it to the end.;
$(function() {
$('.test-input').on('focus', function(evt) {
that = this;
setTimeout(function() {
that.selectionStart = that.selectionEnd = 10000;
}, 1);
});
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="test" class="test-input" value="abcdefgh" />
<input type="text" name="test" class="test-input" value="a1b2c3" />
<input type="text" name="test" class="test-input" value="abcdefghijklmnop" />
Extra:
If you are programming just for mobiles, will be nice to take a look at touchEvents (https://developer.mozilla.org/pt-BR/docs/Web/Events/touchstart)
This should be working just fine the first time you click on the textbox. This is when the focus event is triggered, since you're actually 'focusing on' the item. From then on, until you click anywhere outside the element, your item will already have the focus and therefore will not execute the onfocus event.
The main difference is focus event call any time when you will focus on input field like if you use tab button and focused on input field but in case of click you need to click on input field.
I think that it has to do with the fact that the code executed at the click is executed before focusing on the input and affecting a position to the cursor.
On the other hand, when you listen to the focus event, the cursor has already a position and stays at this position.
That's pure personal theory. However, if you want to make it work, I found a great solution that works in Chrome on this question: Use JavaScript to place cursor at end of text in text input element
You need to clear the value of the input, wait for one millisecond, and reapply the value:
$(function() {
$('#test-input').on('focus', function(evt) {
$target = $(evt.target);
var val = $target.val();
$target.val('');
setTimeout(() => {
$target.val(val)
},1)
});
})
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
I first used the onKeyUp event to detect input changes in a textbox. However, when the user enters in a French character using ALT+Num, the event doesn't detect the change until i enter the next character...
Which event should I be using to detect the special character changes. I've tried onChange but does not seem to be working.
I've tried using onkeypress event because I notice that it triggers it after i release the ALT key, however even though once the ALT is release, the onkeypress is triggered and you see the accented character, but when I use this.value for the inputbox, it only registers up to and before the new ALT+Num character is input.
for example: i entered vidé, but the search would not dynamically find vidé, but only vid because the é has not been saved in the - this.value yet, until another key event is triggered.
Hence I was wondering if there's way to simulate/send a key press to trigger it.
FINALLY FIGURED IT OUT!! :D
here's the code, however the String converting event.which code does not work on the jsFiddle though, nonetheless the code works :)
$('#i').keydown(function() {
document.getElementById('j').value = "down";
$('#k').val($('#i').val())
});
$('#i').keyup(function() {
document.getElementById('j').value = "up";
$('#k').val($('#i').val())
});
$('#i').keypress(function(event) {
$('#k').val(String.fromCharCode(event.keycode));
});
$('#i').change(function() {
document.getElementById('j').value = "change";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="i" type="text" /><br />
<input id="j" type="text" />
<input id="k" type="text" />
View on JSFiddle
use keyup. The new character will not be added until the user releases the ALT key and at that point the keyup event will fire.
There's a reference at http://unixpapa.com/js/key.html which might be a good idea to have a look at, and according to section 2.1, ALT should generate a keydown and keyup in modern browsers..
I would suggest you use jQuery or a similar library to ease the issues you're facing cross-browser. Have a look at http://jsfiddle.net/qvDbu/1/ for a proof of concept which works fine.
Keypress is not triggered by only modifier-presses, so that's probably the way to go, it allows you to pick up the character entered as well, rather then which key is pressed. Edit: Seems to not be the case in Fx that keypress is triggered by modifiers, but I'm not able to reproduce actually loosing any characters.
The character entered with the ALT+NUM combination will only be added to the input element's value after the keyup event triggers, so you won't be able to read it in that event handler.
In order to solve this problem you could set a timeout on the ALT keyup event before reading the input element's value:
$('input').on('keyup', function (e) {
var _this = this;
var ALT_KEY_CODE = 18;
if (e.which == ALT_KEY_CODE) {
setTimeout(function () {
handleKeyup.call(_this , e);
}, 1);
} else {
handleKeyup.call(_this , e);
}
});
function handleKeyup (e) {
// $(this).val() now holds the ALT+NUM char
}
You need to bind onkeypress, which won't fire until you finish entering the alt code.
document.getElementById('input').onkeypress = function() {
alert('fired');
}
<input id='input' type='text' />
View on JSFiddle