DarkArtistry
DarkArtistry

Reputation: 434

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 ''

Upvotes: 0

Views: 367

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

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
}

Upvotes: 2

Shadow Fiend
Shadow Fiend

Reputation: 1829

Its not working and your console is empty because of this line

if(window.matchMedia("max-width: 414px")) {

It must be

 if (window.matchMedia("(max-width: 414px)").matches) {

And transition is not working with display:none and height:auto..

You can try opacity instead of display.

I made a sample fiddle..

And try to look at the console you can see that its not empty anymore.

Upvotes: 2

Related Questions