I have problems using jQuery .css('background-size','contain');
On Google Chrome sometimes it works and sometimes it doesn’t.. (90% of cases it doesn’t work)
Here is the code I’m using:
function scaleImg(){
var img = $('#img_src_div img');
if(img.height() >= 600 || img.width() >= 570){
$('#img_src_div').css('background-size','contain');
}
}
Here is a JSFiddle example, and it is working. But inside my page it is not.
And it’s pretty much the same, there is some php generated content, like urls and some text. and the code it’s inside a parent div.
I tried removing all javascripts that may interfer with it, but it’s the same. In firefox it’s all ok.
EDIT:
images.php – This it’s included on another php page.
//Removed - Was not usefull.
2nd EDIT: By calling scaleImg(); manually after the page is loaded, the background get scaled. So there is a issue on the page load..
This is the exact code i’m using right now.
<script type="text/javascript">
function scaleImg() {
var container = document.getElementById(\'img_src_div\');
var img = container.children[0]; // assuming image is first child
// var img = container.getElementsByTagName(\'img\')[0]; // use this one if not
if( img.width >= 570 || img.height >= 600) container.style.backgroundSize = "contain";
}
$(document).ready(function(){
scaleImg();
});
</script>
3rd and last (hopefully) EDIT:
I’ve solved, the problem was that $(document).ready(...); it’s executed before the image has been fully downloaded. So instead to call scaleImg(); on document ready function, i call it inside onload="" of the image tag.
<img alt="" onload="scaleImg(this.width,this.height);" id="img_src" src="image_url" />
Try plain JavaScript:
It’s possible that jQuery is doing some validation on your CSS call and is failing for some reason. Plain JS is more reliable 😉