Skip to Content

focusOnElement()

Focus on an element for tab navigability or otherwise.

JavaScript February 7, 2021

Usage

JavaScript
nebula.focusOnElement(element)

Parameters

element
(Required) (Object) The element to focus on
Default: None

Parameter Notes

If the element desired to be focused on is not typically focusable, this function makes it temporarily focusable.

Request or provide clarification »

Examples

Scroll to an element and then set tab navigability to start there as well.

JavaScript
jQuery('html, body').animate({
    scrollTop: Math.floor(jQuery(scrollElement).offset().top-offset+pOffset)
}, scrollSpeed, function(){
    nebula.focusOnElement(scrollElement); //Start tab navigability here too
});

Source File

Located in /assets/js/modules/utilities.js on line 130.

No Hooks

This function does not have any filters or actions available. Request one?
JavaScript
nebula.focusOnElement = function(element = false){
    if ( !element ){
        nebula.help('nebula.focusOnElement() requires an element as a string or jQuery object.', '/functions/focusonelement/');
        return;
    }

    //Debounce this because several things could call this simultaneously that cannot be reduced (like hashchange + scrollTo function call)
    nebula.debounce(function(){
        if ( typeof element === 'string' ){
            element = jQuery.find(element); //Use find here to prevent arbitrary JS execution
        } else if ( !element.jquery ){ //Check if it is already a jQuery object
            element = jQuery(element);
        }

        //If the element is not focusable itself, add tabindex to make focusable and remove again
        if ( !element.is(':focusable') ){ //Uses custom expression defined at the bottom of this file
            element.attr('tabindex', -1).on('blur focusout', function(){
                jQuery(this).removeAttr('tabindex');
            });
        }

        element.trigger('focus'); //Focus on the element
    }, 500, 'focusing on element', true);
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.focusOnElement = function(element){
    //Write your own code here, leave it blank, or return false.
}