0

Basically been trying to figure out some javascript stuff, so was making a couple of divs, and a select, so depending on the selected option, depends on what div is shown/hidden.

It seems to work ok, hiding all but the first div after loading, then when the second option is selected, it shows the second div, hiding the first by appending a class.

When I change the option back to the first div though, it creates a long running script that jams everything up and I can't figure out where the long running script comes from.

Any advice appreciated.

Here's the code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <style>
      .itemCont.show{
        display:block;
      }
      .itemCont.hide{
        display:none;
      }
    </style>
  </head>
  <body onload="sortDivs();">
    <select name="options" id="opts" onchange="optSelect(this);">
      <option value="0">item</option>
      <option value="1">another</option>
    </select>
    <div class="output">
      <div class="itemCont show" id="div0">
        <h1>1</h1>
      </div>
      <div class="itemCont" id="div1">
        <h1>2</h1>
      </div>
    </div>
  </body>
  <script async="async" ype="text/javascript">
  function sortDivs(){
    var divs = document.getElementsByClassName('itemCont');
    for( var i = 0; i < divs.length; i++ ){
      if(i>0){
        divs[i].className += ' hide';
      }
    }
  }

  function optSelect(opt){
    var val = opt.value;
    var divs = document.getElementsByClassName('itemCont');
    var divActive = document.getElementsByClassName("itemCont show");
    divActive[0].className = divActive[0].className.replace(/\bshow\b/,'hide');

    for ( var i = 0; i < divs.length; i++ ) {
      if(i = val){
        divs[i].className = divs[i].className.replace(/\bhide\b/,'show');
      }
    }

  }

  </script>
</html>
wsjlisseter
  • 99
  • 1
  • 1
  • 10

1 Answers1

1

You have a typo = should be ==

for ( var i = 0; i < divs.length; i++ ) {
    if(i == val){
        divs[i].className = divs[i].className.replace(/\bhide\b/,'show');
    }
}

I recommend using jQuery (toggle) to handle this kind of stuff though :)

Luis
  • 114
  • 2
  • 10
  • Haha, so simple. Thanks! Why'd you recommend jQuery? Just thought since I'm not going to be using much javascript, loading the library might be a little much. But I'm fairly new at all this javascript stuff. – wsjlisseter May 07 '16 at 13:32
  • you are right! if that's all you are doing then loading jQuery has no benefit but if you continue adding features you will see that a lot of the things you need are already part of jQuery. So, it makes code lean and cross browser compatible (easier to maintain). – Luis May 08 '16 at 12:40
  • Ah, thanks. I'll definitely look at learning more jQuery in case things do get a little more javascripty :) – wsjlisseter May 08 '16 at 14:15