In my focus manager I need to store some info on the last focus and blur. I need to delegate this hook to body, but if I use * as a filter I will receive the focus event for every parent item of the actual thing getting focus.
Realistically, I could make a filter to accept something like a, input, button ... etc, but also I need to refine it to a:not([tabindex]=-1), *[tabindex!=-1] etc.
But this gets complicated when one considers disabled controls. Is there a jQuery selector for :focusable, or how do I work around this? I could debounce my function, but even that is iffy.
EDIT:
Alright, my bad, I think what I am looking for here is :tabbable.
you can check focus by using: $("yourselector").is( ":focus" )
If you want to stop bubbling up to the dom just return false in your function after doing your stuff.enter code here
Related
I have a <form> containing two text <input>s side-by-side. When both of these inputs lose focus, I want to do some stuff (send an Ajax request to server and replace them with something else in the DOM). However if I click or tab from one of the inputs to the other, I don't want to do those things.
Setting an onBlur event handler on the <form> element works fine using my setup, but there doesn't seem to be any way to determine if the other form input is my next target. If I examine document.activeElement in my handler, it points to the <body> element (in Chrome) at that point. Only afterwards does it change to the other input.
Is there any way to reliably do what I'm asking? Solutions involving jQuery or other libraries are fine.
So it turns out that event.relatedTarget was what I was looking for - this will return the DOM node receiving focus on a blur event, so it's just a matter of setting a conditional to see if it matches the other field.
However, while this works great in Chrome, relatedTarget currently isn't implemented properly in other browsers. Apparently there's a couple of workarounds:
In IE11, document.activeElement does actually get set to the receiving element at the time the event fires, so you can use that.
In Firefox, apparently event.explicitOriginalTarget can be used instead.
Try ..
Set a global variable that stores what you last blurred from. Call it x.
Set a blur event on all elements, and set x to the last element you blurred from.
Set a focus event on all elements, and if x is not one of your two elements, then run your script.
Give to them both ids, like this:
<input id="id1" />
<input id="id2" />
Then, with jQuery, you can call blur() nested with the two ids.
$('#id1').blur(function(){
$('#id2').blur(function(){
//do your thing
});
});
I've got a form where I'm trying to do the sort of thing you often see with tags: there's a textfield for the first tag, and, if you put something into it, a new and similar textfield appears to receive another tag. And so on. I've gotten the basics of this working by setting up a jQuery .blur() handler for the textfield: after the value is entered and the user leaves the field, the handler runs and inserts the new field into the form. The handler is pretty vanilla, something like:
$('input.the_field_class').blur(function () { ... });
where .the_field_class identifies the input field(s) that collect the values.
My problem is that, while the new textfield is happily added to the form after the user enters the first value, the blur handler doesn't fire when the user enters something into the newly-added field and then leaves it. The first field continues to work properly, but the second one never works. FWIW, I've watched for and avoided any id and name clashes between the initial and added fields. I had thought that jQuery would pick up the added textfield, which has the same class markings as the first one, and handle it like the original one, but maybe I'm wrong -- do I need to poke the page or some part of it with some sort of jQuery initialization thing? Thanks!
Without seeing your code in more of its context, it's hard to know for sure, but my best guess is that you're attaching a handler to the first field, but there is no code that gets called to attach it to the new field. If that's the case, you have a few options, two of which are:
1) In your blur() handler, include code to attach the blur handler to the newly created field.
2) Use jQuery's event delegation to attach a handler to the field container, and listen for blur events on any field in the container:
<div class="tag-container">
<input class="the_field_class" /> <!-- initial tag field -->
</div>
<script>
var $tagContainer = $('.tag-container');
var createNewField = function() {
$tagContainer.append($('<input class="the_field_class" />');
};
$tagContainer.on('blur', 'input.the_field_class', createNewField());
</script>
Which is better will depend on your use case, but I'd guess that the 2nd option will be better for you, since you're unlikely to be dealing with tons of blur events coming from the container.
I have a large form that contains several text input fields. Essentially, I need to handle the onchange event for all fields and the onblur events for some fields. When a change is made to a field and the field loses focus, both events fire (which is the correct behavior). The only issue is that I would like to handle the onblur
event before I handle the onchange event.
After some testing in ie and Firefox, it seems that the default behavior is to fire the onchange event before onblur. I have been using the following code as a test...
<html>
<body >
<input type="text" value="here is a text field" onchange="console.log('Change Event!')" onblur="console.log('Blur Event!')" >
</body>
</html>
Which brings me to my questions:
It seems that this behavior is consistent across browsers. Why does onchange fire first?
Since I cannot handle the onblur event for every input element, is there a way I can get onblur to fire before handling the onchange event?
The reason onchange fires first is that once the element loses focus (i.e. 'blurs') the change is usually complete (I say usually because a script can still change the element without user interaction).
For those elements that need onblur handled first, you can disable the onchange handler and fire the onchange (or even a custom event) from the onblur handler. This will ensure the correct order even though it is more work. To detect change, you can use a state variable for that field.
As a general remark though, the need for such synchronicity is a sign that the approach you are using to solve whatever problem you are solving might need more work even though sometimes it cannot be avoided. If you are sure this is the only way, try one of these methods!
EDIT: Just to elaborate on the last point, you would have to follow some assumptions about your event model. Are you assuming that each change event is followed by a blur and goes unprocessed otherwise, or would you like to process each change but those that are followed by a blurget further processing after whatever onblur does with them? In any case if you want to enforce the order the handlers would need access to a common resource (global variable, property, etc.). Are there other event types you might want to use? (input?). Finally, this link has some details for the change event for Mozilla browsers:
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/change.
The third 'bullet' addresses the issue of event order.
This is a bit of hack, but it seems to do the trick on most browsers:
<input type="text" value="Text Input" onchange="setTimeout(function(){console.log('Change Event!')}, 0);" onblur="console.log('Blur Event!');" />
You can see a fiddle of it in action here: http://jsfiddle.net/XpPhE/
Here is a little background information on the setTimeout(function, 0) trick: http://javascript.info/tutorial/events-and-timing-depth
Hope that helps :)
I want to know if it's possible to select a textarea's content when it gets modified. In jQuery, I'd do the following:
$("texarea").on("change", function (e) {
$(this).select(); // the content gets selected for copy/cut operations
});
I know it's a bad practice to directly manipulate DOM elements from within an angular controller, so if you know how I can do this cleanly, I'd be happy to learn how!
I think you can do the following, attach an event handler to your textfield element using onblur and onfocus attributes. Write two functions for each as follows:
onfocus get the initial content of the textfield
onblur get the final content and compare to the initial content if there is a difference the run the select function
If you want it to be in real time your could also use onkeyup and onkeydown
I have two inputs that together form a single semantic unit (think an hours and minutes input together forming a time input). If both inputs lose focus I want to call some Javascript function, but if the user merely jumps between those two, I don't want to trigger anything.
I've tried wrapping these two inputs in a div and adding an onBlur to the div, but it never triggers.
Next I tried adding onBlurs to both inputs and having them check the other's :focus attribute through jQuery, but it seems that when the onBlur triggers the next element hasn't received focus yet.
Any suggestions on how to achieve this?
EDIT: Someone questioned the purpose of this. I'd like to update a few other fields based on the values contained by both these inputs, but ideally I don't want to update the other fields if the user is still in the process of updating the second input (for instance if the user tabs from first to second input).
I made a working example here:
https://jsfiddle.net/bs38V/5/
It uses this:
$('#t1, #t2').blur(function(){
setTimeout(function(){
if(!$('#t1, #t2').is(':focus')){
alert('all good');
}
},10);
});
var focus = 0;
$(inputs).focus(function() { focus++ });
$(inputs).blur(function() {
focus--;
setTimeout(function() {
if (!focus) {
// both lost focus
}
}, 50);
});
An alternative approach is to check the relatedTarget of the blur event. As stated in the MDN documentation this will be the element which is receiving the focus (if there is one). You can handle the blur event and check if the focus has now been put in your other input. I used a data- attribute to identify them, but you could equally well use the id or some other information if it fits your situation better.
My code is from an angular project I've worked on, but the principle should translate to vanilla JS/other frameworks.
<input id="t1" data-customProperty="true" (blur)="onBlur($event)">
<input id="t2" data-customProperty="true" (blur)="onBlur($event)">
onBlur(e: FocusEvent){
const semanticUnitStillHasFocus = (val.relatedTarget as any)?.dataset?.customProperty === "true";
// Do whatever you like with this knowledge
}
What is the purpose of this behavior ?
The blur event triggers when a field looses focus, and only one field can gain focus at a time.
What you could do, in case of validation for instance, is to apply the same function on blur for both the fields and check the values of the fields altogether.
Without a context, it is difficult to help you more.
d.