user3378649
user3378649

Reputation: 5354

How to show/hide a span using javascript

Can someone show a way to show/hide a span using javascript

 document.getElementById("test").style.display= 'visible';
 document.getElementById("test").style.display= 'block';

In the HTML Code

<span id='test' ..

How can I overcome this problem. Is there any thing that I should think about?

UPDATE I have a class like this one, I want to force mouse hovering on it.

<div id="test" class="tooltip effect">
        <div id="second" href="#"> .. </div>

On css:

tooltip{..}
effect{..}
effect:hover{..}

Another option I tried besides your code is

document.getElementById("test").onmouseover = test.hover;

Upvotes: 3

Views: 31520

Answers (4)

Nitin
Nitin

Reputation: 11

<span class="text-danger" id="spanAddressLine1" runat="server" style="display: none;"> //Here is your message </span>

JQuery code

For show: $('#<%= spanAddressLine1.ClientID%>').show();

For hide: $('#<%= spanAddressLine1.ClientID%>').hide();

Here spanAddressLine1 is the id of span

Upvotes: 0

gNerb
gNerb

Reputation: 887

Use display none/default:

document.getElementById("test").style.display= 'none';
document.getElementById("test").style.display= '';

Below are some types and some easy to remember rules about them:

Default: the elements default property (generally block or inline)

Block: Generally on a line by itself. Has the width and height attributes (among other size/positioning attributes)

inline: on the same line as other elements/text. Does not have height/width attributes

Inherit: Inherits the parent element's display type

Upvotes: 10

Lajos Arpad
Lajos Arpad

Reputation: 76436

I would do something like this to handle it:

function HideAndSeek(selector) {

    var elements = undefined;
    var displays = [];

    if (!!selector.id) {
        elements = [document.getElementById(selector.id)];
    } else if (!!selector.class) {
        elements = document.getElementsByClass(selector.class);
    }

    for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
        displays[elementIndex] = elements[elementIndex].style.display;
    }

    this.hide = function() {
        for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
            elements[elementIndex].style.display = "none";
        }
    };

    this.show = function() {
        for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
            elements[elementIndex].style.display = displays[elementIndex];
        }
    };
}

This function can be used this way:

var hideAndSeek = new HideAndSeek({id: "test"});

and you can hide the element(s) by:

hideAndSeek.hide();

you can show them by:

hideAndSeek.show();

Upvotes: 0

Sterling Archer
Sterling Archer

Reputation: 22395

visible isn't a value for the display, you want none

Upvotes: 1

Related Questions