How to know if an object can be focused

1

I am making a script to throw errors with javascript and in this function it throws the focus on the field that is with errors. In some cases, when the field is not visible, for example, an error appears in the console, nothing so serious that interrupts my application, the error says that the field is not focusable. As these errors make me uneasy I want to avoid them and so I want to do a conditional to check if a field can be focused with .focus or not.

    
asked by anonymous 28.09.2017 / 18:53

1 answer

4

You can check the visibility, as I did in this response link

function getStyle(elem, prop)
{
    if (elem.currentStyle) { //IE8
        return elem.currentStyle[prop];
    } else if (window.getComputedStyle) {//Navegadores modernos
        return window.getComputedStyle(elem, null).getPropertyValue(prop);
    }
}

function isVisible(elem)
{
    //Verifica inputs
    if (/^(input|select|textarea)$/i.test(elem.nodeName) && elem.type === "hidden") {
        return false;
    }

    //Verifica a propriedade visibility
    if (getStyle(elem, "visibility") === "hidden") {
        return false;
    }

    //Verifica a propriedade display
    if (getStyle(elem, "display") === "none") {
        return false;
    }

    return true;
}

function focalizar(elem)
{
     if (isVisible(elem) && elem.focus) {
         elem.focus();
         return true;
     }

     return false;
}
#ELEMENTO_1 {
    visibility: hidden;
}
#ELEMENTO_3 {
    display: none;
}
<textarea id="ELEMENTO_1">Invisivel visibility: hidden</textarea>
<button onclick="console.log(focalizar(document.getElementById('ELEMENTO_1')));">Focar elemento invisível</button>
<hr>

<textarea id="ELEMENTO_2">Visivel</textarea>
<button onclick="console.log(focalizar(document.getElementById('ELEMENTO_2')));">Focar elemento visível</button>
<hr>

<textarea id="ELEMENTO_3">Invisivel display: none</textarea>
<button onclick="console.log(focalizar(document.getElementById('ELEMENTO_3')));">Focar elemento invisível</button>
<hr>
    
28.09.2017 / 18:57