0

If I click a button I can assign it a function like bellow

document.getElementById("mySidenav").style.width = "250";

This works fine, however I wish do give it a different width for different screen sizes so I was going to set the width in a class so that i can use a css media query. instead of .style.width = "250";how can I tell it to take the values of a CSS class instead ?>

3
  • 2
    developer.mozilla.org/de/docs/Web/API/Element/classList Commented Oct 22, 2018 at 15:33
  • 1
    sounds like you are asking about media queries Commented Oct 22, 2018 at 15:34
  • yep, i will be using a media query in my css Commented Oct 22, 2018 at 15:37

2 Answers 2

2

Just for reference, CSS names cannot start with digits, per the W3C spec. Your edited post removes the need for this comment but it's worth noting.

To manipulate classes via JavaScript, either use className (as in myElement.className = 'some-class') or the classList interface. However, you specifically mentioned "different screen sizes" and this is a prime candidate for responsive CSS queries using the @media selector.

With all that being said:

JavaScript example

// CSS
#mySidenav {
     width: 1000px;
}

#mySidenav.responsive-class {
     width: 500px;
}

// JS

const mySidenav = document.querySelector('#mySidenav');

window.addEventListener('resize', function() {
     if (window.innerWidth < 200) {
          mySidenav.classList.add('responsive-class');
     }
     else {
          mySidenav.classList.remove('responsive-class');
     }
});

CSS example

#mySidenav {
     width: 1000px;
}

@media query and (max-width: 200px) {
     #mySidenav {
          width: 500px;
     }
}

As you can see, the latter example is much simpler. Go with the CSS approach. A halo will appear over you.

Sign up to request clarification or add additional context in comments.

2 Comments

based of your answer I have tried ` document.getElementById("mySidenav").classList.add('popoutwidth');` this seems to do the job. however when i close the div (another function it dose not pop back out.)
@Beep Great. You'll need to provide a working code example (CodePen, JSFiddle) for the community to help you further. It's probably an issue with CSS specificity.
0

I used @Shenh's answer to work out a solution +1 Sheng.

Please see bellow I added new class and removed class

    function openNav() {
    document.getElementById("mySidenav").classList.add('popoutwidth');
    }

   function closeNav() {
    document.getElementById("mySidenav").classList.remove('popoutwidth');
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.