Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find focused element in document with many iframes

I have a document with multiple iframes in it. The iframes all have textareas and textboxes. How can I find out what is the focused element (the element with the cursor in it) in the whole document? I need a method (or a property) which will search in all of the iframes and return the textarea or textbox with the cursor in it.

document.ActiveElement gives me the whole body of the document in console.

like image 876
petko_stankoski Avatar asked Nov 30 '22 11:11

petko_stankoski


1 Answers

I have made it for you. With this function you can get the element active in the web page or iframes. The function checks where is the active element and returns it:

/**
* Return the active element in the main web or iframes
* @return HTMLElement
**/
function getActiveElement() {
    var focused = false;

    // Check if the active element is in the main web or no
    if( document.body === document.activeElement ||
        document.activeElement instanceof HTMLIFrameElement ){

        // Search in iframes
        $('iframe').each(function(){
            var element = this.contentWindow.document.activeElement;
            // If there is a active element
            if( element !== this.contentWindow.document.body ){
                focused = element;
                return false; // Stop searching
            }
        });

    }
    else focused = document.activeElement;

    return focused; // Return element
}

You can see a jsfiddle example working in: http://jsfiddle.net/tgrywLz7/5/

UPDATED:

Even better! With the new function you can get the active element in a webpage with multilevel iframes and without jQuery!:

/**
* Retrieve active element of document and preserve iframe priority MULTILEVEL!
* @return HTMLElement
**/
var getActiveElement = function( document ){

     document = document || window.document;

     // Check if the active element is in the main web or iframe
     if( document.body === document.activeElement 
        || document.activeElement.tagName == 'IFRAME' ){
         // Get iframes
         var iframes = document.getElementsByTagName('iframe');
         for(var i = 0; i<iframes.length; i++ ){
             // Recall
             var focused = getActiveElement( iframes[i].contentWindow.document );
             if( focused !== false ){
                 return focused; // The focused
             }
         }
     }

    else return document.activeElement;

     return false;
};

See in action: http://jsfiddle.net/tgrywLz7/9/

like image 66
SnakeDrak Avatar answered Dec 09 '22 21:12

SnakeDrak