Petru Lebada
Petru Lebada

Reputation: 1682

How to reverse the hide event of a div onclick

I have a div and a button which i would like to show/hide the div when its clicked:

<input type="button" name="info" value="Contact Information" onclick="showDiv()">
<div align="center" id="element" style="display: none;">bla</div>

And this piece of script:

function showDiv() {
   document.getElementById('element').style.display = "block";
   if( ... )
   document.getElementById('element').style.display = "none";
}

The display style of the div is none,so its hidden.The first line of the js script changes that value into block,so the div its displayed now. Now i need something to reverse the first line,in case the button its triggered again.So i thought a conditional statement will do it,but i have no idea how to build it. Something line : "if the display style its block,execute the code between {}" Any idea?

Upvotes: 0

Views: 2657

Answers (3)

gurel_kaynak
gurel_kaynak

Reputation: 554

Using the browser DOM directly is very annoying and your solution may not work in all browsers. You should use some javascript framework like jQuery, prototype or mootools. In jQuery what you want to do is as simple as this:

$("#element").toggle()

If you insist on using raw javascript you can try this:

function showDiv() {
   if( document.getElementById('element').style.display == 'block' )
   document.getElementById('element').style.display = "none";
   else
   document.getElementById('element').style.display = "block";
}

Upvotes: 2

yunzen
yunzen

Reputation: 33449

Edit

function toggleDiv(elementId, button, textOn, textOff) {
  var style = document.getElementById(elementId).style;
  if( style.display == "none" ) {
    style.display = "block";
    button.innerHTML = textOn;
  } else {
    style.display = "none";
    button.innerHTML = textOff;
  }
}
<button name="info" onclick="toggleDiv('element', this, 'Hide Contact Information', 'Show Contact Information')">Show Contact Information</button>
<div align="center" id="element" style="display: none;">bla</div>


Original Answer


function toggleDiv() {
    if( document.getElementById('element').style.display == "none" ) {
        document.getElementById('element').style.display = "block";
    } else {
        document.getElementById('element').style.display = "none";
    }
}

Upvotes: 3

Manjunath D R
Manjunath D R

Reputation: 371

<input type="button" name="info" value="Contact Information" onclick="showDiv()">
<div align="center" id="element" style="display: none;">bla</div>
<script>
function showDiv() {
   var div = document.getElementById('element').style.display;
   if( div == 'block' )
      document.getElementById('element').style.display = "none";
    else 
    document.getElementById('element').style.display = "block";
}
</script>

Upvotes: 0

Related Questions