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

Asked

Viewed 1,965 times

4

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

I know how to do it with jQuery, that’s how:

 $('.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?

  • What is the problem with the question? Could I explain?

  • 4

    apparently is the if(user == 4995) downvote();

  • 2

    A: Use jQuery :p

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, the attribute type="hidden" in the element <input>.

With getComputedStyle (and currentStyle) we were able to check the property visibility and display, both in the attribute style="" how much on the tag <style>, as in properties within CSS files that are affecting elements on the 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
  • I didn’t know this function, but anyway you don’t always use CSS class to hide or show an element.

  • @Klaiderklai that doesn’t just parse CSS, it parses the attribute style=""

  • @Wallacemaxters as well?

  • Forget it, I want to avoid debates for today

  • @Guilhermenascimento Err, but I said that the OP could use that condition if it is changing the visibility of the element only with the display, because I didn’t know otherwise. But I know it’s more correct to use this function quoted in your answer.

  • @Klaiderklai I’m almost there, but it’s still a bit difficult for me, if you mean setar via javascript: element.style.display="none";?

  • @Guilhermenascimento Exactly.

  • @Klaiderklai but that’s what I said, the currentStyle and the getComputedStyle recognize the style.display="none", because reading them is from what this "rendered" and not from what this in the CSS file :)

  • @Yes, I know. My answer only works with display defined in any CSS inline.

  • @Klaiderklai It was bad, I didn’t even see that the answer was yours, so I’m floating... but then, it’s very common for people to use the attribute class="" to hide things, only using el.className = "" :)

  • @Guilhermenascimento Well, jQuery probably changes the style online. My method just won’t work with anything outside define the display...:... online. I will make an update !

  • 1

    @Klaiderklai Ahh understood, in this case to use .hide or .animate will be the same element.style.display, but it is very common in jQuery to use too .addClass, your answer is yes for the case of AP (this is a great answer to your ;) ), only that we usually try to make the relevant answers to the whole community ;) (of course this is not mandatory)

Show 7 more comments

3

Use the method window.getComputedStyle();

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

This method assesses whether the element or one of his parents is invisible.

  • You see, I took negative, but it was good to ask. This one I didn’t know :D

2

If you are changing the visibility of the element only with the property display (inline) CSS, so you can make this condition 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 display mode is undefined, "initial", "block", "inline-block" or other types.

2

You can use the 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>

Browser other questions tagged

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