In CSS I set a button to be 100px x 100px and have the background-size: contain;
In javascript I apply an image to the element that I do not have the Height/width of (nor aspect ratio) .
In another function in javascript I need to be able to get the size of the image/background of this button after it has passed through the contain function.
Is there any way to do this (I have access to Jquery as well)
Small Sample:
<style>
#imageButton{
width: 100px;
height: 100px;
background: url("imageURL");
background-size: contain !important;
}
</style>
<script>
var imageElem = $('#imageButton')[0];
console.log($(imageElem).width());
//100px but need width of image after scaling
</script>
Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.
background-size:100%; = background-size:100% auto; = the width is set to be 100% large and the height of the background image follows respecting the image aspect ratio.
cover tells the browser to make sure the image always covers the entire container, even if it has to stretch the image or cut a little bit off one of the edges. contain , on the other hand, says to always show the whole image, even if that leaves a little space to the sides or bottom.
CSS property background-size: contain;
scales the image to the largest so that both the height and width will fit inside, retaining the same aspect ratio of course.
Just like @Teemu said, A background image is a kinda pseudo element which you actually can't refer. But I can show you a workaround on how to get the real image size and compute the scaled background-image size.
It works like ratio and proportion where:
real_image_width is to real_image_height as resized_image_width is to resized_image_height
First we need to get the real size of the image:
var img = new Image;
img.src = $('#imageButton').css('background-image').replace(/url\(|\)$/ig, "");
var imgW = img.width;
var imgH = img.height;
Then, compare which dimension is the largest and calculate the proportion:
var newW, newH;
if(imgW > imgH){
newW = $('#imageButton').width(); //100;
newH = imgH / imgW * newW;
}else{
newH = $('#imageButton').height(); //100
newW = imgW / imgH * newH;
}
console.log(newW+':'+newH);
If the image is not yet loaded or cached it will return a size of 0, a good way to fix this is to get the size when the image is has been loaded using .load()
function.
Browsers also differ in sub-pixel rendering, I think you need to round off to nearest .5 decimal to get the exact safest value (43.7832 => 43.5). Using: (Math.round(value * 2) / 2).toFixed(1)
That's it! Here is the sample fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With