Home > Blockchain >  How do i auto hide a div when selecting a second div in Javascript?
How do i auto hide a div when selecting a second div in Javascript?

Time:06-02

I'm having a hard time trying to figure out what's wrong in my code. As i call the function clean() it cleans the screen without ever showing a <div>. If i call the function togglevisible() it shows the div i clicked on, although on a new element click it doesn't hide the first element, unhiding the second element below the first element. How can i hide an element after clicking on a new one in Javascript? This is the code i'm using atm:

function clean() {
  if (previous_value !== null) {
    var hide = document.getElementById(previous_value);
    hide.style.display = "none";
  }
  togglevisible();
}

function togglevisible() {
  var dropdown = document.getElementById("dropdownCenterBtn");
  var current_value = dropdown.options[dropdown.selectedIndex].value;
  var previous_value = current_value;
  
  if (current_value !== null) {
    var selected = document.getElementById(current_value);
    selected.style.display = "flex";
  } else {
    var selected = document.getElementById(current_value);
    selected.style.display = "none";
  }
}
<div >
  <select  id="dropdownCenterBtn" onchange="clean()">
    <option>Courses List</option>
    <option>------------</option>
    <option value="div1">Introduction to Computer Science</option>
    <option value="div2">Web Programming with Python and Javascript</option>
  </select>
</div>

<div  id="div1">
  <h3>Introduction</h3>
</div>

<div  id="div2">
  <h3>Web Programming</h3>
</div>

CodePudding user response:

You went way too far. Here's a quick solution for that.

function clean(event) 
{
  var divs = document.querySelectorAll(".div");
  
  divs.forEach(function (div){
    if(div.id === event.target.value && div.style.display == "none")
        div.style.display = "flex";
    else if(div.style.display !== "none")
        div.style.display = "none";
  });
}
<div >
  <select  id="dropdownCenterBtn" onchange="clean(event)">
    <option>Courses List</option>
    <option>------------</option>
    <option value="div1">Introduction to Computer Science</option>
    <option value="div2">Web Programming with Python and Javascript</option>
  </select>
</div>

<div  id="div1">
  <h3>Introduction</h3>
</div>

<div  id="div2">
  <h3>Web Programming</h3>
</div>

  • Related