Prathamesh Prabhudesai Prathamesh Prabhudesai - 4 months ago 11
HTML Question

CSS-Javascript: Show and Hide div

I want to create a menu where there is just title and a view more link is provided.
If that link is clicked it should open a hidden div and that view more should change to show less or close. And if I click that the div should close again.
So far I have this.

Title 1 <a href="#" onclick="showdiv()">View More</a>
<div id="title1_div">
Some Information
</div>

<style>
#title1_div{
display:none;
}
</style>

<script>
function showdiv()
{
document.getElementById('title1_div').style.display = 'block';
}
</script>


This only provides the on click show division. How can I close that div on clicking.

Any help would be appreciated.

Please see this example at JSFiddle: https://jsfiddle.net/eo4cysec/

Answer

You just check if the property is set to block, if so you set it to none, else you set it to block. So you have a toggling logic in it.

if(document.getElementById('title1').style.display == 'block') {
   document.getElementById('title1').style.display = 'none';
} else {
   document.getElementById('title1').style.display = 'block';
}

To set the text to View Less you need the reference of the clicked tag, you pass it as parameter like this:

<a href="#" onclick="showdiv(this)">View More</a>

Then you have the chance to use this parameter and set the innerHTML of it, which is the text that is displayed. So the final function will look like this, where e is now the reference on the a-tag:

function showdiv(e) {
  if(document.getElementById('title1').style.display == 'block') {
     e.innerHTML = 'View More';
     document.getElementById('title1').style.display = 'none';
  } else {
     e.innerHTML = 'View Less';
     document.getElementById('title1').style.display = 'block';
  }
}

Please check out this fiddle:

https://jsfiddle.net/g7ry88h7/