简体   繁体   中英

How to get the focus event following the blur event?

I like to know what the onFocus event is (if there will be any) when I receive an onBlur event in my (javascript) handler. How is this possible?

Example: I have a group of textboxes that form one group. Only if the whole group loses focus I want to inform subscribers about the group onBlur event. So if an onBlur event occurs I only want to forward it when I notice that it's not followed by an onFocus event on another textbox in the group..

I do this now through a delay and looking if a focus event occurred in the meantime. But I don't like this solution so much as: because of the delay the blur occurs after the focus and the event that it contained in the delayed blur is "old" which can be tricky in further processing..

My idea was: looking in the "event queue", when I receive the blur event, to detect any onFocus event that will follow... But I have no idea if this is possible and how to do this :(...

-- Edit:

Having reviewed your question I'm not quite sure what you're asking, so I'm not sure if what I've posted is suitable. Regardless, I leave it here for consideration.

You can do it quite trivially with a map and the 'this' variable:

var map = new Object();

...

function doBlur (obj) {
   if(map[obj] == "focus"){
   }
}

function doFocus (obj) {
    map[obj] = "focus";
}

<input onblur="doBlur(this);" onfocus="doFocus(this);" />

But even further, given that only one textbox can be focused at a time, you can just have a variable named lastFocus , and check that that object equals the one you want.

The focus and the blur event should be added to the event queue, so a simple 1-100 ms setTimeout would probably do the trick.

I know you aren't using jQuery - but its easier for me to air code an example using it:

var blurTimeout;

function blurAlert() {
   alert('Lost Focus');
}

// assign these two simple functions to all inputs on the page.
$('input').blur(function() {
  blurTimeout=setTimeout(blurAlert, 1);
}).focus(function() {
  clearTimeout(blurTimeout);
});

I just tested it out at 1ms in firefox, I'm pretty sure that timing will hold well for other browsers as well. Because of the way events are handled, blur fires, then focus, then the timer.

If you really want to make sure to keep the this around from the event your event handler turns into:

 function() { 
   blurTimeout = setTimeout(function() {
     blurAlert.apply(this,arguments);
   }, 1);
 }

You can use delegation method for blur and focus
So you will check what was focused.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM