简体   繁体   中英

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/

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/

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';
}

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> 

$('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');
   }
}),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM