I'm writing a form validation script and would like to validate a given field when its onblur event fires. I would also like to use event bubbling so i don't have to attach an onblur event to each individual form field. Unfortunately, the onblur event doesn't bubble. Just wondering if anyone knows of an elegant solution that can produce the same effect.
You're going to need to use event capturing (as opposed to bubbling) for standards-compliant browsers and focusout for IE:
if (myForm.addEventListener) {
// Standards browsers can use event Capturing. NOTE: capturing
// is triggered by virtue of setting the last parameter to true
myForm.addEventListener('blur', validationFunction, true);
}
else {
// IE can use its proprietary focusout event, which
// bubbles in the way you wish blur to:
myForm.onfocusout = validationFunction;
}
// And of course detect the element that blurred in your handler:
function validationFunction(e) {
var target = e ? e.target : window.event.srcElement;
// ...
}
See http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html for the juicy details
use 'Focusout' event as it has Bubble up effect..thanks.
ppk has a technique for this, including the necessary workarounds for IE: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
aa, you can simply add the onblur event on the form, and will call the validation every time you change focus on any of the elements inside it
Related
I'm writing a form validation script and would like to validate a given field when its onblur event fires. I would also like to use event bubbling so i don't have to attach an onblur event to each individual form field. Unfortunately, the onblur event doesn't bubble. Just wondering if anyone knows of an elegant solution that can produce the same effect.
You're going to need to use event capturing (as opposed to bubbling) for standards-compliant browsers and focusout for IE:
if (myForm.addEventListener) {
// Standards browsers can use event Capturing. NOTE: capturing
// is triggered by virtue of setting the last parameter to true
myForm.addEventListener('blur', validationFunction, true);
}
else {
// IE can use its proprietary focusout event, which
// bubbles in the way you wish blur to:
myForm.onfocusout = validationFunction;
}
// And of course detect the element that blurred in your handler:
function validationFunction(e) {
var target = e ? e.target : window.event.srcElement;
// ...
}
See http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html for the juicy details
use 'Focusout' event as it has Bubble up effect..thanks.
ppk has a technique for this, including the necessary workarounds for IE: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
aa, you can simply add the onblur event on the form, and will call the validation every time you change focus on any of the elements inside it
I'm trying to build a shortcut expander, so when a user types a certain sequence of characters, it's replaced with some longer sentence.
I'm currently using 'input' event to capture contenteditable changes. The issue is, pasting also triggers the 'input' event. I only want the event to fire when user types in a character. Is there any way to do this?
The simplest solution would be to detect a keyboard event (keydown, keyup or keypress) instead of oninput, but which to choose, depends on what the handler actually will do.
If you don't want/can't use keyboard detection, there's a back-gate. It looks like onpaste would fire before oninput (Chrome, FF). Hence you could create a flag for paste, and check it in oninput handler. Something like this:
var pasted = false,
pad = document.getElementById('pad'); // The contenteditable
pad.addEventListener('paste', function (e) {
pasted = true;
});
pad.addEventListener('input', function (e) {
if (pasted) {
pasted = false;
return;
}
console.log('keyboard, cut or drop');
});
A live demo at jsFiddle.
Notice, that oninput is fired also ondrop and oncut as well as onpaste and typing in. If you don't want to handle any of these events in oninput handler, you've to listen all these events, and set a flag accordingly.
As a sidenote, IE doesn't fire oninput on contenteditables. If you want to support IEs, you need to use onkeypdown/up-onpaste-oncut-ondrop combination to achieve something similar to oninput.
I am trying to set a listener that listens for all focus events. In particular I am trying to listen for anytime an input or textbox gains focus. Per some research, the widely accepted way to achieve this is like this:
document.body.onfocus = function(event) {
//Check the event.target for input/textbox
//Do something
};
But the document.body.onfocus doesn't seem to fire, ever. I thought it might be because the document doesn't actually ever receive focus so I tried:
document.body.focus();
To initially "set" the focus, but this doesn't work either.
Any ideas on how I can listen to a focus event on all inputs/textboxes without actually setting the event directly on the element itself? Vanilla javascript only please, I am not using a framework.
Per the accepted answer here is some working code:
var focusHandler = function(event) {
var type = event.target.nodeName.toLowerCase();
if(type == 'input' || type == 'textarea') {
//Do something
}
};
document.body.addEventListener('focus', focusHandler, true); //Non-IE
document.body.onfocusin = focusHandler; //IE
As some events (focus, blur, change) do not bubble up, I would recommend you to try Event Capturing instead. First of all onfocus will not work for this, so you have to use addEventListener where you are able to specifiy the used delegation mode in the third argument. Look at MDN for the use of addEventListener.
And take a look at this article for further information about delegating the focus event up.
The focus event doesn't bubble from elements up to their ancestor elements, so you can't use event delegation (hooking it on body and seeing it for all descendants of body) to detect it.
There's a newer event, focusin (a Microsoft innovation, now also available in other browsers), which does bubble, so that may work for you depending on which browsers you want to support.
I have an <input> element that can either have the focus set via code, or as the result of a mouse click.
If the user clicks on the input, then the click event handler will fire - all well and good. If the element receives the focus via some other way (e.g. via code) then I want to manually trigger the click event so that the handler will also fire.
I could do this:
$elem = $('input');
$elem
.on('focus', function() { $(this).trigger('click') })
.on('click', function() { alert('Clicked!') });
However, this will result in click handler being fired twice; once for the click event and once for the focus event.
Is there any way to selectively trigger the click handler only if the focus was not received as the result of a click event?
UPDATE
This is a very simplified version of my problem, so I can't do things like bind both handlers to the focus event etc. I'm trying to merge two third-party pieces of code.
The .trigger() function adds a property isTrigger in the event object to identify that the event was triggered by its usage. Although, it is not documented the property is still present in jQuery 1.8.3 but it seems to only be used internally.
Anyways, you can make use of the extraParameters parameter to add a custom property to the event object. For instance,
$(this).trigger('click', {
isTrigger: true
});
It will keep the compatibility with isTrigger even if it is gone in a future release.
After doing some more research it appears that there is no way of guaranteeing which event will fire first: click or focus. (There doesn't seem to be a standard that dictates the order of events.)
This means that when the focus event fires there's no way to determine if a click event will or will not be triggered by the browser shortly afterwards.
I managed to solve the issue by using setTimeout() to run a test about 100ms after the focus event fired to check if the click event had fired. The third-party code that I was using (bound to the click event) added an extra class to the <input>, so I was able to check for that.
You can tap into the mousedown event which fires before the focus event. When you click a focusable object the order of events is as follows... mousedown, focus, mouseup, click.
You could set a flag in the mousedown event and then check for it in the focus event to see if the focus came from a mouse click. Obviously make sure to clear the flag in the focus event handler. Every application is different, but tapping into the mousedown event allows you to figure out a solution.
Here is a JSFiddle demonstrating the order of events... http://jsfiddle.net/ek7v7/
$elem = $('input');
$elem
.on('focus', function() { alert("Focused!") })
Focus can be fired by focusing the input by using tab, clicking it, or by using .focus()
Is there a reason for on('click', ...)?
With the following html structure:
<div>
<form><span><input></span></form>
</div>
<p>
and the following jquery code:
$('form').on("focus", function(event) {
$("p").append("focus no delegation<br>");
})
Why doesn't the focus event ever reach my event handler? Binding the event with a selector parameter works fine:
$('form').on("focus", "input", function(event) {
$("p").append("focus delegation<br>");
})
Event the next snippet works so the focus event does in fact bubble...
$('form').on("focus", "span", function(event) {
$("p").append("focus delegation<br>");
})
Both forms work with click and change events:
$('form').on("click", function(event) {
$("p").append("click no delegation<br>");
})
$('form').on("click", "input", function(event) {
$("p").append("click delegation<br>");
})
The only note I found about the focus event's bubbling is relative to older jQuery versions which I don't use. See it in action here
edit 1
Well this is confusing... According to jQuery's focus doc:
The focus event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping focus to the focusin event in its event delegation methods, .live() and .delegate().
And according to jQuery's focusin doc:
The focusin event is sent to an element when it, or any element inside of it, gains focus. This is distinct from the focus event in that it supports detecting the focus event on parent elements (in other words, it supports event bubbling).
Is it too late for me or does one contradict the other?
As Ohgodwhy pointed out, using focusin instead of focus does work.
However, I can't understand how the following code can work if the "focus" event does not bubble:
$('form').on("focus", "span", function(event) {
$("p").append("focus delegation<br>");
})
If a span child of the form receives the "focus" event, it means that the event bubbled from the input to the span. Even this works!
$('div').on("focus", "form", function(event) {
$("p").append("focus delegation<br>");
})
So... using "focusin" does fix the problem, but I'm not fully satisfied by this workaround. If anybody has a better answer, I'll happily accept it.
Yes, it appears the jQuery docs are misleading. I believe the documentation on focus neglected to mention that this was for the elements that aren't involved in user input (#Ohgodwhy listed them above in your question's comments).
I imagine it has something to do with the browser's need to trap the cursor in the input element that has focus, so that it can accept input from the keyboard. In other words, if jQuery allowed it to bubble, then you would never be given the chance to type in the input field.
Either way you'll never get a form to accept a focus event unless you first put a tabindex on it: http://jsfiddle.net/qxLqP/ but if an input based field gets focus first, it will never bubble. By default, the form element doesn't have a tabindex, and you can't set focus to something that doesn't have a tabindex.
I'd just accept #Ohgodwhy's solution of using focusin and then go let the jQuery team know about their confusing documentation.
Jquery has a cross browser function which takes care of focus delegations.
Chrome,safari and opera support an event called "DOMFocusIn" which actually delegates.
IE supports an event "focusin" for delegating focus.
Firefox supports "focus" only on capturing phase and not bubbling phase.
jQuery made a cross browser event which is "focus" which actually delegates.
I hope this answers all your doubts.