开发者

How do i find the new focus item with jquery?

I have a pop up dialog that lets you write text and does stuff when you click a button. My code is below

This function works, i find the new object by looking at e.originalEvent.explicitOriginalTarget. However now i notice if i press tab this function will be called but e.originalEvent.explicitOriginalTarget will give me the same current object instead of the new object. So my dialog doesnt close if a user presses tab to leave. How do i find the correct new dom item?

$('#Area').focusout(function (e) {
    if ($(e.originalEvent.explicitOriginalTarget).closest('#Area').size() == 开发者_如何学Go0)
        $('#Area').hide();
});


event.relatedTarget worked for me. It will give the other DOM element, within the event, if there is one.

An example would be, if you had 2 buttons controlling the same function, and didn't want their code to be executed if they were clicked consecutively. You could attach a focusout event handler and check for an ID, or a class name.

$(".buttons").on("focusout", function (event) {
    if($(event.relatedTarget).prop("class").indexOf("buttons") === -1) {
        //code to execute
    }
});

Perhaps a better example would be the issue I had.

I created a custom drop down list, that has a button beside it. The drop down list can be opened and closed by either clicking on the list, or the button. It can also be closed be losing focus to either object.

This becomes a problem in the following scenario. 1) user opens drop down list by clicking the list object. 2) user closes drop down list by clicking the button.

What happens is the list opens, but when the user goes to close the list, the list loses focus, which closes it, but since they are clicking on the button, it opens back up. The focusout causes the two objects to cancel each other out, in this type of scenario.

By writing the focusout event, I can now set it to only trigger when the relatedTarget doesn't have the same class as the target that called the event.

$(".listControl").on("focusout", function (event) {
    if($(event.relatedTarget).prop("class").indexOf("listControl") === -1) {
        //Close the drop down list
    }
});

http://api.jquery.com/event.relatedTarget/


Check out this question/answer How to select an element that has focus on it with jQuery

I think the reason why you don't get anything with $("*:focus"); in Firebug console is when you click the console, the element loses focus.

And if you want to tackle it with events, the opposite of focus() is blur().


Edit

Maybe you can even try a different approach. If your only concern is watching for tab key, you can use .keypress() event and watch for tab keycode which is 9.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜