Get window width and height

3

I wanted to get the width and height of the window, so that if my page is viewed in different resolutions, if I position the window. Because with different resolutions, the page either becomes 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 by changing the position

    
asked by anonymous 19.02.2015 / 11:29

1 answer

1

To do this using javascript only, you can use the innerHeight and innerWidth properties. 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 added the event onresize to window . If the current window size is less than 300px within that event ( resize ), it will cause body to have background-color red, and otherwise green.

There's also a way to do this through Media Queries .

See an example:

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

    document.body.style.backgroundColor = 'red'

})

You may notice that the screen and (max-width) snippet looks a bit like the CSS syntax.

Note: Remembering that document.body.style.backgroundColor = 'red' is just an example, and instead, your operation should be applied according to the need you need to detect window size.     

19.02.2015 / 12:01