JavaScript FocusOut - get the element that receives focus

后端 未结 4 780
青春惊慌失措
青春惊慌失措 2021-02-13 13:03

When the FocusOut event is raised, how do you know which element receives the focus?

The correct way seems to be to use the event\'s relatedTarget p

4条回答
  •  粉色の甜心
    2021-02-13 13:07

    I have encounter the same problem using textEditor PrimeFaces element.

    I use the following html code.

    The TextArea is defined twice so that when form is displayed, the user see only the first

    widget without seeing a specific toolbar.

    When user click on text displayed, the focusin() event hide the

    element and display the widget contained in
    parent element.

    To do that, I have defined the following javascript code

    function onLoadDialog()
        {
        jQuery(".text-editor").hide();
    
        jQuery(".div-focus").focusin(function()
            {
            $(this).hide();
            $(this).next(".text-editor").show();
            $(this).next(".text-editor").focus();
            });            
    
        jQuery(".text-editor").focusout(function(e)
            {
            if ($(e.relatedTarget).closest(".text-editor").size() == 0)
                {
                $(this).hide();
                $(this).prev(".div-focus").show();
                $(this).prev(".div-focus").text($(this).text());
                }
            });            
        }
    

    The onLoadDialog function() is called when page is loaded and is used to hide

    element and display
    element. When the user clicks on text in
    element, this element is hidden and the following hidden element is display. The
    element gains focus.

    The focusout() event hide

    element and display
    element ... only when element that gains focus is not defines in
    element.

    The problem with element.focusout() is that it is triggered each time an element included in main element even if element that gains focus is defined in same element.

    When you enter in a house, you can enter passing by garage or living room or kitchen. When you enter in living room (by external door), you enter in the building. But when you quit living room to kitchen, you stay in house !!! If you quit living room to go in garden, you quit the house (building).

    focusin() function implement the same principe, but not focusout() !

    if ($(e.relatedTarget).closest(".text-editor").size() == 0) line used in focusout() event correct this little difference !

    CAUTION: the solution is not perfect because I have some little problems to solve when copying text from textEditor widget to outputText widget without formatting !

提交回复
热议问题