Home > database >  Capture window size in Javascript
Capture window size in Javascript

Time:10-26

At the moment I have the problem that I have a transparent navbar and if the screen is less than 300px in width it should get white. How can I get the window size?

CodePudding user response:

Some more explanation would be nice since it's not really clear what you are trying to achieve.

Reading your question as is, your best bet would be to use a media query and style the navbar with CSS based on this media query. No need for JS:

<style>
nav {
  width: 100vw;
  height: 100px;
  background-color: transparant;
}

@media (max-width: 299px) {
  nav {
    background: white;
  }
}
</style>
<nav></nav>

CodePudding user response:

In JS you can do this using window.matchMedia(), like this:

if (window.matchMedia("(max-width: 300px)").matches) {
  /* Make navbar white. */
}

You could combine this with an event listener that triggers when the viewport gets resized (e.g. window.addEventListener('resize', ...);)

You can also do this in CSS with media queries:

@media (max-width: 300px) {
  .navbar {
    background-color: white;
  }
}
  • Related