How do I activate a div with Javascript?

Asked

Viewed 496 times

2

I have the following problem I have a <div> hidden above login field:

<div id="MostraLegenda" class ="legenda" style ="display: none">
    <p>Login do Usuario</p>
</div>

She’s with the display: none, want to use the event onmouseover and put it as display: block.

JS:

function mostrarLegenda()
{
    var div;
    div = document.getElementById("MostraLegenda");
    div.setAttribute.apply("style", "display:block");
    return true;
}

2 answers

2

To change the style of an element you can access the properties using elemento.style.[propriedade]

function mostrarLegenda()
{
    var div;
    var estilo;
    div = document.getElementById("MostraLegenda");
    estilo = div.style.display;
    div.style.display = (estilo == 'none') ? 'none' : 'block';

    return true;
}
  • worked out, just one more question, I can compare with an if so if(div.style.display == 'None'){

  • 1

    Can you, just check if( elemento.style.display == 'none' //ou 'block')

1


To make the element appear, use the following code to return the property style of this object that will give you access to the element’s CSS.

See the example below using your own function:

function mostrarLegenda() {
    document.getElementById("MostraLegenda").style.display = 'block';
}

You can also use an automated way to appear/disappear:

function mostrarLegenda() {
    var div = document.getElementById("MostraLegenda");

    if (div.style.display == 'none') {
        div.style.display = 'block';
    } else {
        div.style.display = 'none';
    }
}

Browser other questions tagged

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