My code:
<input class="quantity" type="text" value="33000">
<script>
$(document).ready(
$('.quantity').keyup(function (event) {
alert('up');
MyVeryImportantValidate($(this), event.key)
});
..
</script>
My problem, if introduced into the Input still holding the keys and mouse make click on any other element in page... event keyup does not work.
I think the documentation in jquery states it clearly, it is going to the item that has focus.
http://api.jquery.com/keyup/
The keyup event is sent to an element when the user releases a key on
the keyboard. It can be attached to any element, but the event is only
sent to the element that has the focus. Focusable elements can vary
between browsers, but form elements can always get focus so are
reasonable candidates for this event type.
In fact the focus is lost even on holding a key down in this input text area. If I hold down the a letter key it repeats until I click outside it changing the focus.
Related
I need to have a list of checkboxes with the condition that at least one of them must be checked.
The following code produces that effect.
document.querySelector('div').addEventListener('click', function(evt){
if( this.querySelectorAll('input:checked').length == 0 )
evt.preventDefault() ;
}) ;
<div>
<input type=checkbox checked>
<input type=checkbox>
<input type=checkbox>
</div>
That's fine, however, I don't understand why this code even works.
Firstly, I'm doing a .preventDefault() on the click event only after I've checked the condition that says there are no checkboxes checked. So canceling the click event at this point should make no difference.
Secondly, the code works even if you try to check the checkboxes using the keyboard, which is totally weird because I'm only canceling the click event.
Please explain why the code works the way it does.
While an input event listener is running, its effect on the element's state is actually already performed. If event.preventDefault() is called, this change is undone when the listener returns. This allows a checkbox event handler to test the new state of the checkbox, and allows the handler for a keyboard event on a text input to test the value that includes the new input.
The reason it works when you use the keyboard is that the click event is a high-level event that encompasses all the different ways to click on a checkbox: you can do it with the mouse, with they keyboard, with a touchscreen, etc. If you want to listen to a specific mode of clicking, you would have to use mousedown, keypress, etc.
Context
I have a backbone app with an event listener for focus events on a textarea. Backbone uses jQuery events, so core of my question centers around jQuery focus events.
Question
Is there a way to tell how an element came into focus, be it by click or tab?
The behavior of how the cursor gets positioned needs to be handled differently between these two cases, however there doesn't seem to be a way to distinguish between the two offhand.
I could listen to click events, however will still need to listen to focus to capture tabbing - this will overlap with click event as it will also focus the textarea resulting in double events.
I may to rethink this entirely.
JSBin Example
$('textarea')
.focus(function(event){
console.log('You focused me by' + event.type);
// Here I wish I know if the focus came from a 'click' or 'tab' events
});
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form>
<input placeholder="focus me, then tab" type="text"><br>
<textarea>Focus me via click. Now try via tabbing.</textarea>
</form>
</body>
</html>
.onfocus() listener can get called in a number of ways which makes it a tricky even to bind to.
Click on element
Tab or Shift-Tab to element
jQuery programatic focus $( "#target" ).focus();
Switching between programs, and refocusing the internet browser
There is no unique identifier in the onfocus event to determine how it came into focus.
From what I found it is best to be more explicit and listen to click() and onkeyup() events to handle unique behaviors between them and avoid unexpected function calls (like the browser is refocused).
onkeyup() is great for capturing tab events as the tab key will be released 'up' when tabbing in, but not when tabbing out.
JSBin
$('textarea')
.click(focusedBy)
.keyup(checkTab);
function checkTab(event){
if (event.keyCode === 9) {
focusedBy(event);
}
}
function focusedBy (event){
console.log('You focused me by ' + event.type);
}
you will need a combo of focus, click and blur events to determine the origin of "getting focus". click->set value, focus -> check if that clickvalue was set -> do what you must -> reset on blur. you might also want to be looking out for ontouchdown
You could set a clicked variable on mousedown.
You'll need to blur the textarea on mousedown so that focus will will be triggered on mouseup:
var clicked= false;
$('textarea')
.focus(function(event) {
if(clicked) {
$('#status').html('clicked');
clicked= false;
}
else {
$('#status').html('tabbed');
}
})
.mousedown(function(event) {
clicked= true;
$(this).blur();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input placeholder="focus me, then tab" type="text"><br>
<textarea>Focus me via click. Now try via tabbing.</textarea>
</form>
<div id="status"></div>
here's a scaling way to do it without rerouting events or simulating extra actions:
var targ=$('textarea');
targ.focus(function(event){
console.log('You focused me by ' + targ.eventType);
// Here I wish I know if the focus came from a 'click' or 'tab' events
});
$("body").mousedown(function(e){
targ.eventType="mouse";
}).keydown(function(e){
targ.eventType="keyboard";
});
this uses the jQuery collection to store the last event type, which is set by document-wide handlers.
if you need to re-use this functionality on other input types, just add more selectors to targ and differentiate in the handler using event.target.
http://jsbin.com/ruqekequva/2/edit
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
});
In the following example, I get only one alert box. I read that the focus is put before the JavaScript code is executed. Is there a way to get this to work on?
<input id="i" type="text" autofocus onfocus="alert(1)">
<script type="text/javascript">
document.getElementById('i').addEventListener('focus', function() {
alert(2);
}, false);
</script>
(I have only tested this in Safari)
Edit:
I can obviously do it this way (Prototypejs selector):
var autofocusElement = $$('input[autofocus]')[0];
callListener(autofocusElement);
But it looks ugly compared to only add an event listener.
Edit:
Do not worry over a lack of browser support for the autofocus attribute. It solved easily as I have done in I fiddle links to below. There is also the best solution to the problem as I can see. My question is if I can do it in a less ugly than having to call the listener manually.
http://jsfiddle.net/tellnes/7TMBJ/3/
It works fine in Firefox 3.6 since Firefox does not support autofocus. But in Safari, which supports autofocus, are not the event called.
From the HTML5 working draft:
There must not be more than one
element in the document with the
autofocus attribute specified.
So you're asking for undefined behavior anyway.
With only one autofocus element, under Firefox 3.6, neither of the handlers get called on page load. Manually giving the focus to the element calls both handlers (then proceeds into an infinite loop, due to the alert boxes giving the focus back to the element when closing).
The HTML5 draft does say that autofocus should perform the focusing steps on page load, including raising the focus event, but chances are that browsers are not currently implementing that feature in a complete or consistent manner.
You might want to explicitly call your focus event handler during page load until the HTML5 spec is finished and browsers start aiming for complete support.
The following code from your current example:
<input id="i" type="text" autofocus onfocus="alert(1)">
<script type="text/javascript">
document.getElementById('i').addEventListener('focus', function() {
alert(2);
}, false);
</script>
Is going to cause an infinite loop of alerts going from 1 to 2
[eidt]
because: (this happens only in broswers that support autofocus )
input gets autofocus, fires event which fires an alert, alert grabs focus, click ok, input grabs focus, focus event fires new event triggering now two different alerts (DOM fully loaded now so new event is added with another alert), both alerts grab focus, click ok, click ok, input grabs focus fires new event triggering now two different alerts, alert grabs focus, click ok, next alert grabs focus, click ok, input grabs focus, fires both events, alert grabs focus, click ok, next alert grabs focus, click ok, input grabs focus, fires both events, alert grabs focus, click ok, next alert grabs focus, click ok, input grabs focus, fires both events, alert grabs focus, click ok, next alert grabs focus, click ok, input grabs focus, fires both events, input grabs focus, fires both events, alert grabs focus, click ok, next alert grabs focus, click ok, input grabs focus, fires both events, input grabs focus, fires both events, alert grabs focus, click ok, next alert grabs focus, click ok, input grabs focus, fires both events, input grabs focus, fires both events, alert grabs focus, click ok, next alert grabs focus, click ok, input grabs focus, fires both events...
Textual description of an infinite process FTW!....? :P
[/edit]
In your previous examples with two auto-focuses applied it seems that the last one will be executed as in the example I have attached at the bottom. I also added a way of adding a focus event to each input based on a class name... Not sure if you're looking for that but though it might be of some help.
JSFiddle Example of onfocus event
You need to give a value to autofocus.
<input id="i" type="text" onfocus="alert(1)" autofocus="">
Give autofoucs="autofocus" attribute after all events has been given to the input field.
You can also use addEventListener in .js file at the top.
It might be that the autofocus onfocus event fires before addEventListener adds the event listener.
I replaced autofocus with class="autofocus" on my input element, and set the focus like this near my addEventListener call:
if(searchInput.classList.contains('autofocus')) {
searchInput.focus();
}
If you need to execute a piece of javascript code, onfocus for either input, you could use jQuery: http://api.jquery.com/focus/
Just wondering whether anyone knows what events an HTML5 <input type="number" /> element fires when its up / down arrows are clicked:
I'm already using an onblur for when the focus leaves the input field.
change would be the event that is fired when the field's value changes.
I think the HTML5 event input would also fire.
I found that for jQuery the following code covered keyboard input, mousewheel changes and button clicks in Chrome, and also handled keyboard input in Firefox
$("input[type=number]").bind('keyup input', function(){
// handle event
});
I found that onkeyup and onchange covered everything in Chrome 19.
This handles direct value input, up down arrow keypress, clicking the buttons and scrolling the mousewheel.
onchange alone would be sufficient in Chrome, but other browsers that only render the field as a text box need the onkeyup binding, which works perfectly to read the new value.
Binding the mousewheel event separately was less successful. The event fired too early - before the field value was updated - and therefore always gave the field's previous value
The onchange event fires on blur but the oninput event fires as you type. Maybe you might want to put a timer on the oninput event and fire your onchange event when the user has stopped typing for a second?
There is a current bug in Edge preventing change or input from firing when using the arrow keys in a number input.