mercredi 1 juillet 2015

Responsive Design - Toggle a Div's Visibility - how to integrate javascript with css @media

I started a previous thread with the same goal but now I have the real question and have created two fiddles jsfiddle #1 AND jsfiddles jsfiddle #2 to show the problem.

I am attempting to use principles of responsive design to adapt to changing screen size. It has these two parts

  • Use CSS to hide/show a vertical menu div (main-nav-vert) using @media based on browser width.

  • Use a Menu button to also hide/show the same div main-nav-vert using javascript.

The problem I am having is that I can find a way to integrate the javascript with the @media rules. I am open to another way (but without jQuery)

The Problem: To test these fiddles and see the problem: Reduce the window size to see the impact of @media and it should hide the menu on the left. Expand the window and the menu should reappear. Now shrink the window again until the menu disappears. Click the button and the menu appears. Click the button a second time to hide it. NOW, expanding the window will no longer show the menu.

Try #1 (jsfiddle #1)

  • javascript changes the same display property of main-nav-vert that @media is changing.
  • javascript only changes the element NOT the underlying CSS (as shown in the inspector).
  • The element values set by javascript will take precedence over the CSS property set by @media and so ...
  • once the button is pressed, the @media settings will no longer work - being overridden.

Try #2 (jsfiddle #2)

  • javascript alternately sets a new class to the main-nav-vert div (hidden and visible) with each click of the button.
  • the display property for main-nav-vert set by @media will take precedence over the display property from the hidden class and the button will not hide the menu ... UNLESS
  • I override the display property by using !important in the visible and hidden classes, but then @media won't work as before.

Please help. There must be a better way. I am looking for a pure js answer, please no jQuery. Thanks.

Aucun commentaire:

Enregistrer un commentaire