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>
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 :)