DarkArtistry DarkArtistry - 23 days ago 9
CSS Question

Edit Media queries CSS with event listener

I have an unordered list

<ul>
that I would like to add an event listener too
if it fits a certain media query.

The original css :

@media (max-width: 414px) {
transition: all 3s ease-out;
height: 0px;
display: none;
}


the eventlistener function :

if(window.matchMedia("max-width: 414px")) {
console.log(list.style.height);
console.log(list.style.display);
list.style.height = 'auto'
list.style.display = 'unset'
}


HELP : the transition seems not to be working & the console log for list.style.height & list.style.display is both empty ''

Answer Source

The transition won't work because you are changing display from/to none. In addition, you need to transition the height between numeric values (auto doesn't count).

CSS:

@media (max-width: 414px) {
    transition: all 3s ease-out;
    height: 0;
}

JS:

if (window.matchMedia("(min-width: 414px)").matches) {
  list.style.height = list.style.height + 'px'; // set the exact height
}