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/

Upvotes: 0

Views: 81

Answers (4)

ScientiaEtVeritas
ScientiaEtVeritas

Reputation: 5278

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/

Upvotes: 1

Pugazh
Pugazh

Reputation: 9561

Here is a working example.

function showdiv(el) {
  if (el.innerHTML == "View More") {
    document.getElementById('title1').style.display = 'block';
    el.innerHTML = "Show Less";
  } else {
    document.getElementById('title1').style.display = 'none';
    el.innerHTML = "View More";
  }
}
#title1 {
  display: none;
}
Title 1
<div id="title1">
  Some Information
</div>
<a href="#" onclick="showdiv(this)">View More</a>

Upvotes: 1

Sami
Sami

Reputation: 3800

Simple function. Call it on click and it'll handle the hide/show:

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

Upvotes: 1

Wim Mertens
Wim Mertens

Reputation: 1790

$('a').click(function () {  
  $(this).next('div').stop(true, true).slideToggle("fast");

if($(this).html() == 'View More'){
       $(this).html('View Less');
   } else {
       $(this).html('View More');
   }
}),

Upvotes: 0

Related Questions