When a user was focused on a particular element when they pressed the tab key, I want to execute a particular function. But I don't want to this function to execute unless that particular element had focus when the tab key was pressed.
Is there a way to to tell what element had (has?) focus from the keydown event itself? Or should I set a particularElementHasFocus property in response to onBlur and onFocus events on that element?
You can use document.activeElement to get current focused element.
or
use
following code
var particularElementHasFocus ;
$('input, textarea, button').focus(function() {
particularElementHasFocus = this;
});
$('input, textarea, button').blur(function() {
particularElementHasFocus = null;
});
Using jQuery it could be done by testing the .focus of the element in question. With standard JS you can use document.activeElement - https://developer.mozilla.org/en-US/docs/DOM/document.activeElement
Related
On my page, I have multiple text boxes and need at least one of those boxes to always have focus. Is there a js event listener I can call that will detect when nothing on the page has focus, so I can give it focus?
If you want to know if an element from a list of tags is focused :
function hasFocus(selector) {
return Array
.from(document.querySelectorAll(selector))
.some(function(el){
return el === document.activeElement
});
}
// usage
console.log(hasFocus('input, select, textarea'))
You can also attach a focusout handler to the document which checks the focusable elements every time a focusout event bubbles up. Then force focus on an element other than the source of the blur event, if none have it.
Edited per comment.
Please check out my solution on this link: https://codesandbox.io/s/nostalgic-lovelace-f9hei
When you load the page, the first input get focus. Everytime you click out. A random input get focused.
blur event will not bubble up by default. So make it bubble up by changing usecapture to true.
const inputs = document.querySelectorAll('input')
document.querySelector('input').focus()
document.addEventListener('blur', (e) => {
console.log(e)
if (e.isTrusted) {
const random = Math.round(Math.random() * (inputs.length-1));
console.log(random)
Array.from(inputs)[random].focus()
}
},true)
I have a view with a form. The form has many inputs, and I would need detect when the user moves between them (clicking or pressing 'tab').
For now I have this:
$('input').on('click',function(){
// Do something
});
But I would need detect if the user focus on these input even if he doesn't use the mouse.
Thank you
How about focus?
$('input').on('focus',function(){
// Do something
});
The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>).
https://api.jquery.com/focus/
For all text inputs inside the form
$(document).ready(function () {
$('form').on('focus blur', 'input', function () {
// Handle event
});
});
You need to use focus event instead of click:
$('input').on('focus',function(){
// Do something
});
I have added change event on the input field so that whenever user enters the text into it, so other task should happen, it works but when i click outside the input field.I don't know whether it is default behavior or i am doing some thing wrong. I tried using keyup and keydown events and it works as expect.
Please suggest.
Here is my code:
$("#mobile-number").on('change',function(){
// some other code
});
The change event fires when an elements value changes.
For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
In other words, on an input, the change event fires when the element loses focus, not when you type, and that is the default behaviour.
That's why there are key events as well, and on modern browsers you can catch most changes to an input with the input event
$("#mobile-number").on('input',function(){ ...
Yes, it is the desired behavior.
Change Event
The change event is fired for , , and
elements when a change to the element's value is committed by the
user. Unlike the input event, the change event is not necessarily
fired for each change to an element's value.
Depending on the kind of form element being changed and the way the
user interacts with the element, the change event fires at a different
moment:
When the element is activated (by clicking or using the keyboard) for and ;
When the user commits the change explicitly (e.g. by selecting a value from a 's dropdown with a mouse click, by selecting a
date from a date picker for , by selecting a file
in the file picker for , etc.);
When the element loses focus after its value was changed, but not commited (e.g. after editing the value of or ).
Try using input event:
$(function() {
$("#mobile-number").on('input', function() {
$("#copy").val(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='text' id='mobile-number' />
<input type='text' id='copy' readonly/>
Try this:( If i really understand your problem )
jQuery(document).on('change', '#mobile-number', function() {
// some other code
});
for type event:
jQuery(document).on('keyup', '#mobile-number', function() {
// some other code
});
You should provide your selector to the .on function:
$(document).on('change', '#mobile-number', function() {
// some other code
});
Is it possible to detect when the user unfocuses an input box using jquery? I.e when they click off of it an event fires.
I believe the blur function is what you are looking for.
$( "input[type=text]" ).blur( function() {
// unfocus event
});
The blur event will fire any time an element loses focus.
If you are trying to determine when any input element on the page loses focus, then use input as your selector.
$("input").blur(function() {
//This event fires every time any input element on the page loses focus
});
If you are only trying to determine when a particular input element on the page loses focus, then using the element's id is the most efficient jQuery selector.
$("#exampleID").blur(function() {
//This event fires if the element with an id of "exampleID" loses focus
});
When using jquery .change on an input the event will only be fired when the input loses focus
In my case, I need to make a call to the service (check if value is valid) as soon as the input value is changed. How could I accomplish this?
UPDATED for clarification and example
examples: http://jsfiddle.net/pxfunc/5kpeJ/
Method 1. input event
In modern browsers use the input event. This event will fire when the user is typing into a text field, pasting, undoing, basically anytime the value changed from one value to another.
In jQuery do that like this
$('#someInput').bind('input', function() {
$(this).val() // get the current value of the input field.
});
starting with jQuery 1.7, replace bind with on:
$('#someInput').on('input', function() {
$(this).val() // get the current value of the input field.
});
Method 2. keyup event
For older browsers use the keyup event (this will fire once a key on the keyboard has been released, this event can give a sort of false positive because when "w" is released the input value is changed and the keyup event fires, but also when the "shift" key is released the keyup event fires but no change has been made to the input.). Also this method doesn't fire if the user right-clicks and pastes from the context menu:
$('#someInput').keyup(function() {
$(this).val() // get the current value of the input field.
});
Method 3. Timer (setInterval or setTimeout)
To get around the limitations of keyup you can set a timer to periodically check the value of the input to determine a change in value. You can use setInterval or setTimeout to do this timer check. See the marked answer on this SO question: jQuery textbox change event or see the fiddle for a working example using focus and blur events to start and stop the timer for a specific input field
If you've got HTML5:
oninput (fires only when a change actually happens, but does so immediately)
Otherwise you need to check for all these events which might indicate a change to the input element's value:
onchange
onkeyup (not keydown or keypress as the input's value won't have the new keystroke in it yet)
onpaste (when supported)
and maybe:
onmouseup (I'm not sure about this one)
With HTML5 and without using jQuery, you can using the input event:
var input = document.querySelector('input');
input.addEventListener('input', function()
{
console.log('input changed to: ', input.value);
});
This will fire each time the input's text changes.
Supported in IE9+ and other browsers.
Try it live in a jsFiddle here.
As others already suggested, the solution in your case is to sniff multiple events.
Plugins doing this job often listen for the following events:
$input.on('change keydown keypress keyup mousedown click mouseup', handler);
If you think it may fit, you can add focus, blur and other events too.
I suggest not to exceed in the events to listen, as it loads in the browser memory further procedures to execute according to the user's behaviour.
Attention: note that changing the value of an input element with JavaScript (e.g. through the jQuery .val() method) won't fire any of the events above.
(Reference: https://api.jquery.com/change/).
// .blur is triggered when element loses focus
$('#target').blur(function() {
alert($(this).val());
});
// To trigger manually use:
$('#target').blur();
If you want the event to be fired whenever something is changed within the element then you could use the keyup event.
There are jQuery events like keyup and keypress which you can use with input HTML Elements.
You could additionally use the blur() event.
This covers every change to an input using jQuery 1.7 and above:
$(".inputElement").on("input", null, null, callbackFunction);