How can I do to detect the visibility of an element (without jQuery)?

4

How do I know if a particular element is not visible with pure Javascript?

I know how to do this with jQuery, which looks like this:

 $('.btn').click(function () {
      $('#box').is(':visible') ? $('#box').hide() : $('#box').show();
 });

But what about pure Javascript? What is the most efficient way to know if an element in the DOM is visible or not?

    
asked by anonymous 29.06.2016 / 21:18

4 answers

5

I disagree with the other answer, style.display is only for inline properties, for this you will have to use getComputedStyle , currentStyle , attribute type="hidden" on element <input> .

With getComputedStyle (and currentStyle ) we are able to check the visibility and display properties, both in the style="" attribute and in the <style> tag, and in properties within CSS files that are affecting elements in current page.

function getStyle(elem, prop)
{
    if (elem.currentStyle) { //IE8

        //Converte hifens para camelCase
        prop = prop.replace(/-([a-z])/gi, function (value) {
            return value.toLowerCase();
        });
        
        return elem.currentStyle[prop];
    } else if (window.getComputedStyle) {//Navegadores modernos


        //Converte camelCase para hifens
        prop = prop.replace(/([A-Z])/g, '-$1').toLowerCase();
        
        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 isHidden(elem)
{
     return !isVisible(elem);
}
#ELEMENTO_1 {
    visibility: hidden;
}
#ELEMENTO_3 {
    display: none;
}
<div id="ELEMENTO_1">Invisivel visibility: hidden</div>
<button onclick="console.log(isVisible(document.getElementById('ELEMENTO_1')));">Testar visibility: hide</button>
<hr>

<div id="ELEMENTO_2">Visivel</div>
<button onclick="console.log(isVisible(document.getElementById('ELEMENTO_2')));">Testar Visivel</button>
<hr>

<div id="ELEMENTO_3">Invisivel display: none</div>
<button onclick="console.log(isVisible(document.getElementById('ELEMENTO_3')));">Testar display: none</button>
<hr>

<input type="hidden" id="ELEMENTO_4">
<button onclick="console.log(isVisible(document.getElementById('ELEMENTO_4')));">Testar input[type=hidden]</button>

Examples:

var el = document.getElementById("meuId");

alert(isVisible(el)); //Retorna true se visivel, caso contrário retorna false

alert(isHidden(el)); //Retorna true se oculto, caso contrário retorna false
    
29.06.2016 / 21:33
3

Use the window.getComputedStyle(); method

var escondido = window.getComputedStyle(document.getElementById("element")).display === 'none';

This method evaluates whether the element or one of your parents is invisible.

    
29.06.2016 / 21:25
2

You can use offsetParent for this, see the example below:

<script>
  function isHidden(id) {
    var elemento = document.getElementById('teste');
    if (elemento.offsetParent === null) {
      elemento.style.display = 'block';
    } else {
       alert('Agora não ve mais!')
      elemento.style.display = 'none';
    }
  }
</script>

<div id="teste">
  Você me ve?
</div>

<button onclick="isHidden()">
  Clica aqui!
</button>
    
29.06.2016 / 21:40
2

If you are changing the visibility of the element only with the display (inline) property of the CSS, then you can do this to check if the element is visible:

var box = document.getElementById("box");

if(box.style.display !== "none") {
    /* Bloco */
}

box.style.display !== "none" will return true if the view is undefined, "initial" , "block" , "inline-block" or other types.

    
29.06.2016 / 21:21