0

I am try to toggle between js style properties

element.style.display and it behaves weird

Found that is easier toggling classes but would like to know the reason it behaves that way

Hi guys if I’m not wrong when I take an ul element using document.getElement in js it is “converted” into a js object so I can acces it through properties with the display attribute being something like {display: block} so if I applied the following code inside a callback used in a myButton.addEventListener(‘click’, callback)

func callback(){ ul.style.display = (ul.style.display === ‘block’) ? ‘none’ : ‘block’; }

It toggles between ‘block and ‘none’

But why when i write it like this:

func callback(){ ul.style.display =y (ul.style.display === ‘none’) ? ‘block’ : ‘none’; }

The display only toggles after the second click

I found that it is easier to just toggle using classList.toggle() between the class with ‘block’ and ‘none’ but I would like to the te reason why the first way behaves that way. It is driving me crazy hahahaha

  • 1
    Please provide a [mre] with your HTML. – Unmitigated Jan 31 '23 at 02:12
  • What is the default value of ul.style.display? – Geshode Jan 31 '23 at 02:15
  • The reason why the 2nd one isn't working as expected is that the property is not defined by default (it returns an empty string). Try using `getComputedStyle(ul).display` in your condition. – Christopher Jan 31 '23 at 02:15
  • Checking CSS properties directly is [best avoided](/q/55071684/4642212), especially for color values. Instead, a CSS class should be used, e.g. `.hidden { display: none; }`; then [`.classList.contains("hidden")`](//developer.mozilla.org/en/docs/Web/API/Element/classList) to check for its existence, `.classList.toggle("hidden", condition)` for setting the class iff `condition` is true, etc. Consider using the [`hidden` attribute](//developer.mozilla.org/en/docs/Web/HTML/Global_attributes/hidden) with [`toggleAttribute`](//developer.mozilla.org/en/docs/Web/API/Element/toggleAttribute) instead. – Sebastian Simon Jan 31 '23 at 04:08

0 Answers0