-4

Working

tutorial.onclick = function(){      
    var tutorial = document.getElementById("tutorials-ul");    
    tutorial.style.display = "list-item";    
}

Not working

news.onclick = function(){    
var news = document.getElementById("news-ul");    

if(news.style.display == "none") {     
  news.style.display = "list-item";    
}

else if(news.style.display == "list-item") {    
   news.style.display = "none";
}    
}

Any answer or opinion is accepted.

kaladont
  • 11
  • 4

2 Answers2

2

I assume the outer news is a button that has already been assigned to a variable (or the default global via its ID).

The issue is if the element itself does not have a display set in its style attribute, then its initial value will be "" instead of whatever was given in CSS.

Therefore instead of comparing to "none", compare to "".

news.onclick = function() {
  var news = document.getElementById("news-ul");
  if (news.style.display == "") {
    news.style.display = "list-item";
  } else {
    news.style.display = "";
  }
}
#news-ul {
  display: none
}
<button id=news>CLICK FOR NEWS</button>

<ul id="news-ul">
  <li>TEST
</ul>
0

I figured it out using this stack overflow Get a CSS value with JavaScript

The correct code for showing and hiding the nested uls is

news.onclick = function(){

var news = document.getElementById("news-ul");

function compareDisplayValue(){

var element = document.getElementById("news-ul");

var style = window.getComputedStyle(element);

var display = style.getPropertyValue('display');

if(display == "none"){

 news.style.display = "list-item"; 

}

else if (display == "list-item"){

 news.style.display = "none";

}

}

compareDisplayValue();

}

kaladont
  • 11
  • 4