bhv
bhv

Reputation: 5378

find width of the image using JavaScript, while image added as background-image in css

have to find the image natural width, heigth

but image added form css as a background-image

html, body {
    height: 100%;
    margin: 0;
}

.image {
    height: 50%;
    border: 1px solid orange;
    background-repeat: no-repeat;
    background-image: url('https://unsplash.it/200/300?image=0');
}
<div class="image"></div>

demo

Upvotes: 0

Views: 51

Answers (2)

Top-Bot
Top-Bot

Reputation: 892

You can get the attribute value using jQuery like this

var image_width = $(".image").width()); var image_height = $(".image").height());

I am posting this from my phone so forgive the in formatted code

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074276

See comments:

// Get the image
var img = document.querySelector(".image");
// Get its current style
var style = window.getComputedStyle ? getComputedStyle(img) : img.currentStyle;
// Extract the URL from it
var match = /url\("?([^")]+)"?\)/.exec(style.backgroundImage);
if (match) {
  // Create an `img`
  var x = document.createElement('img');
  // Watch for when it loads (it'll presumably come from cache)
  x.onload = function() {
    // Now we know its natural size
    console.log("width = " + x.width + ", height = " + x.height);
    console.log("naturalWidth = " + x.naturalWidth + ", naturalHeight = " + x.naturalHeight);
  };
  // Set the src (AFTER hooking 'load')
  x.src = match[1];
}
html, body {
    height: 100%;
    margin: 0;
}

.image {
    height: 50%;
    border: 1px solid orange;
    background-repeat: no-repeat;
    background-image: url('https://unsplash.it/200/300?image=0');
}
<div class="image"></div>

Details on the regex here. Basically, it extracts the path within the url(...) omitting "s.

Of course, if you don't have to get the URL from the element's background-image, all the better...

Upvotes: 1

Related Questions