mICHAEL
mICHAEL

Reputation: 55

How can I dynamically get browser height and width?

What im looking to do is create a chatbox that doesn't rely on media queries. That mathematically sets sizes of the chatbox content.

I was experimenting with $(window).height()/$(window).width() but that doesn't cover the whole browser window. I wanted to do this all in javascript/jquery without css/media queries

Upvotes: 3

Views: 17441

Answers (5)

Mehdi Salimi
Mehdi Salimi

Reputation: 21

If you want to set the maxWidth or minWidth browser screen size like media query dynamically in JavaScript and then define styles or anything else, you can use the Window interface's matchMedia() method. It will return a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.

Ok, the syntax :

const pageWidth = window.matchMedia('(min-width: 600px)');

and we can use the object that returns in different ways:

     const handlePageColor = () => {
    if (pageWidth.matches) {
        document.body.style.backgroundColor = "yellow";
    }
};

And finally you should addListener() method to our object, this causes our function to run whenever the browser screen size changes.

    pageWidth.addListener(handlePageColor);

Upvotes: 0

Dani Amsalem
Dani Amsalem

Reputation: 1616

I ran into a similar problem relating to a nav bar that needed a click event handler on mobile and a hover event handler on desktop. Eventually I found the JS media query function matchMedia() which worked well with setTimeout() so it doesn't run on every pixel change.

My solution can be found here: https://stackoverflow.com/a/60837961/7353382

Upvotes: 0

Momin
Momin

Reputation: 3320

Try this code snippet

(function() {
  window.onresize = displayWindowSize;
  window.onload = displayWindowSize;

  function displayWindowSize() {
    let myWidth = window.innerWidth;
    let myHeight = window.innerHeight;
    // your size calculation code here
    document.getElementById("screen").innerHTML = myWidth + "x" + myHeight;
  };


})();
<div id="screen"></div>

Upvotes: 9

Ivan86
Ivan86

Reputation: 5708

If $(window).height() is not returning the whole browser window size then you have structural issues, like the <!DOCTYPE html> might not be the first line of your HTML file, etc.

Upvotes: 0

David Calhoun
David Calhoun

Reputation: 8571

window.innerWidth and window.innerHeight will give this answer in native JavaScript without any library.

If you want to get the dimensions of a specific HTML Element, you could instead use offsetWidth and offsetHeight, e.g. document.body.offsetWidth

Not exactly sure what you're doing without seeing your code, but when you divide height by width as you do above, you only get a ratio, which is probably why you're not seeing the results you expect?

Upvotes: 0

Related Questions