1

I have a list of items I'm displaying with the html below. Each item has a hidden div with more details about the item. I have made it so if I click the onclick link it shows the div for that specific item. What I want to know is how I would make it hide the div I just opened if I use the onclick to display another items details? Also how could I make it toggle itself when the same onclick is clicked? My knowledge of javascript is somewhat limited so any help would be appreciated. Thanks!

HTML

<div>Item Name <a onclick="FullItemDetails(123)">Full Item Details</a></div>
<div>other stuff</div>
</div>
<div id="FullItemDetails_123" style="display: none;"></div>

And JAVASCRIPT

<script>
function FullItemDetails(item_id)  { 
document.getElementById("FullItemDetails_" + item_id).style.display = "block";
}
</script>

Each div with the extra info has a FullItemDetails_ ID followed by the items unique ID.

Z Kubota
  • 155
  • 1
  • 3
  • 11
Born2DoubleUp
  • 109
  • 1
  • 10

2 Answers2

2

You could find its current css display property to toggle visibility like this

function FullItemDetails(item_id)  { 
  var currentItem = document.getElementById("FullItemDetails_" + item_id);

  if (currentItem.style.display === "block") {
    currentItem.style.display = "none";
  } else {
    currentItem.style.display = "block";
  }
}
Zhephard
  • 360
  • 1
  • 13
1

You can also do it with an event listener, se my example

var elements = document.getElementsByClassName('item')


for(var key in elements){
  
 elements[key].querySelector('.button').addEventListener('click', function(e){
    
  e.target.parentNode.querySelector('#description').style.display = 
    e.target.parentNode.querySelector('#description').style.display == 'none' ? 'block' : 'none'
   
  })
}
<div class="item">Item Name Full Item Details
  <div >Other stuff</div>
  <div id="description">Description</div>
  <button class="button">Toggle</button>
</div>

  <div class="item">Item Name Full Item Details
  <div >Other stuff</div>
  <div id="description">Description</div>
   <button class="button">Toggle</button>
</div>

  
  <div class="item">Item Name Full Item Details
  <div >Other stuff</div>
  <div id="description">Description</div>
 <button class="button">Toggle</button>
</div>

  
Stefan Avramovic
  • 1,365
  • 2
  • 11
  • 20