Ben Holness
Ben Holness

Reputation: 2707

Can I determine the actual width/height of an element on a web page?

To illustrate my question, here is a not-real example:

<img src='myimage-low.png' style='width: 150px;'>
<img src='myimage-high.png' style='width: 150px;'>

myimage-low.png is 150px x 100px

myimage-high.png is 1500px x 1000px

When I am zoomed all the way out on the web page, both images look the same. When I zoom in, the high definition image looks much better.

If I use javascript to get the image width with $(elem).width();, it says (as I would expect) 150px for both, regardless of the zoom.

Is there a way in javascript to get the actual screen size of the element as presented to the user? In my above example, they might both say "100px" when I'm fully zoomed out, and "1000px" when I'm fully zoomed in.

Note - I need to be able to need this for both <img> elements as well as any element that might have a css background-image.

For context, this is to determine which resolution of an image to load. There's no point in loading the 1500px if the user is on a low resolution and it will just be resized in the browser to 300px - they might as well have the 500px version which is faster to download.

Upvotes: 3

Views: 254

Answers (2)

awarrier99
awarrier99

Reputation: 3855

You can use the visualViewport API to multiply the width by the scale if you're looking for pinch zoom:

const { scale } = window.visualViewport;
const width = $(elem).width() * scale;

I tried adding a snippet for an example, but according to the spec the window.visualViewport.scale inside of an iframe is always 1. As long as your content is not in an iframe, this method will work for giving you the scale of the pinch zoom (tested in my browser console)

Upvotes: 1

blex
blex

Reputation: 25634

Say hello to window.devicePixelRatio:

var el = document.querySelector('img');

function getElemSize(el) {
  var rect = el.getBoundingClientRect();
  return {
    width: Math.round(rect.width * window.devicePixelRatio),
    height: Math.round(rect.height * window.devicePixelRatio)
  };
}

function updateSize() {
  var size = getElemSize(el);
  document.querySelector('p').innerHTML = JSON.stringify(size);
}

el.addEventListener('load', updateSize);
addEventListener('resize', updateSize);
<img src="https://howitworks.wpengine.com/wp-content/uploads/2015/09/214887-puppies-cute-puppy.jpg" style="width: 150px">
<p></p>

Upvotes: 4

Related Questions