Get window width and height

Asked

Viewed 2,519 times

4

I wanted to get the width and height of the window, so that if my page is viewed in different resolutions, the window will be positioned. Because, with different resolutions, the page either gets small or large.

example:

<svg width="980" height="500" viewBox="0 0 1200 500">
  <rect ry=0 rx=0 x=50 y=20 width=300 height=200 fill=HoneyDew/>
</svg>

This object is not always the same size changing position

  • As soon as I gave the answer, you added this excerpt from SVG. So, I don’t know if my answer would be valid.

1 answer

2

To do this using javascript only, you can use the properties innerHeight and innerWidth. They will return the current size of your window.

Example:

window.addEventListener('resize', function(){

    if (window.innerWidth < 300) {
        document.body.style.backgroundColor = 'red'
    } else {
        document.body.style.backgroundColor = 'green'
    }

})

We add the event onresize in window. If the current window size is smaller than 300px within that event (resize), he will do the body have the background-color the colour red; or the colour green.

There is also a way to do this through Media Queries.

Take an example:

window.matchMedia('screen and (max-width:300px)').addListener(function()
{

    document.body.style.backgroundColor = 'red'

})

You can observe that the stretch screen and (max-width) looks a bit like CSS syntax.

Note: Remembering that document.body.style.backgroundColor = 'red' is just an example, and, in its place, should be applied to its operation, according to the need you need when detecting the window size.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.