How to know if an object can be focused

Asked

Viewed 56 times

1

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

1 answer

4


You can check the visibility, as I did in this answer /a/137851/3635

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.