How do I activate a div with JavaScript?

2

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

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

It has display: none , I want to use the onmouseover event and set it to display: block .

JS:

function mostrarLegenda()
{
    var div;
    div = document.getElementById("MostraLegenda");
    div.setAttribute.apply("style", "display:block");
    return true;
}
    
asked by anonymous 13.12.2017 / 13:34

2 answers

1

To get the element to appear, use the following code to return the style property 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';
    }
}
    
13.12.2017 / 13:47
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;
}
    
13.12.2017 / 13:40