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.