bsr
bsr

Reputation: 58742

Toggling Visibility with JavaScript

New to JavaScript, and wonder how to use the below code to toggle a <div> visibility:

var toggle = {

    show : function(obj) {

        document.getElementById(obj).style.display = '';

    },

    hide : function(obj) {

        document.getElementById(obj).style.display = 'none';

    }

};

Upvotes: 0

Views: 307

Answers (4)

alex351
alex351

Reputation: 1964

The link for hiding your DIV:

<a href="#" onclick="toggle_visibility('example'); return false;">Hide example div</a>

Example DIV:

<div id="example"></div>

You have to set the DIV to hidden in your CSS:

#example {
 display:none;}

And the Javascript:

<script>

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
</script>

Upvotes: 0

arnexmx
arnexmx

Reputation: 16

To display a div you do: toggle.show('myElement')

To hide it: toggle.hide('myElement')

Of course, you'd need an element id named 'myElement' somewhere in your DOM.

Upvotes: 0

Nosrac
Nosrac

Reputation: 144

Assuming you have HTML like this:

<div id="tooltip"></div>
<span id="blah"></span>

In javascript you'll run the following:

toggle.show("tooltip"); // shows the div with an id of "tooltip"
toggle.hide("blah");    // hides the span with an id of "blah"

Upvotes: 4

Karl Laurentius Roos
Karl Laurentius Roos

Reputation: 4399

I'd recommend checking out jQuery. In jQuery you could do this in one line:

$("#my_obj").toggle();

Speeds up development quite a lot and doesn't leave a huge foot print either.

Upvotes: 1

Related Questions