Cole
Cole

Reputation: 459

Get the size of background-image with jQuery after containing with CSS

#img {
    width:300px;
    height:300px;
    overflow:hidden;
    background-repeat: no-repeat !important;
    background-position: center !important;
    background-size: contain !important;
    color:#fff;
}
    $('#get').click(function () {
        var width = $('#img').css('background-size').width();
        var height = $('#img').css('background-size').height();

        alert('Width: ' + width + ' Height: ' + height);
    });

    //I DON'T want the size of the orginal image. I want the size after the background size has been contained. 

<div id="img" style="background:url(http://img.phombo.com/img1/photocombo/987/cache/wide-wallpaper-1440x900-013_display.jpg) #1BA5E0;">
</div>
    <p>
        <button id="get">Get Contained Size</button>

I want to get the original background image size but after the background has been contained (after this action has been done: background-size:contain;) with jQuery. Is it possible to do that?

http://jsfiddle.net/QyfG2/

Upvotes: 4

Views: 11613

Answers (6)

GVJ
GVJ

Reputation: 67

Use below code this might help you to get background size after contain

function get(img){

    var imageSrc = $(img).css('backgroundImage')
                   .replace(/url\((['"])?(.*?)\1\)/gi, '$2')
                    .split(',')[0];    
    var image = new Image();
    image.src = imageSrc;
    var bgwidth = image.width,
    bgheight = image.height,    
    bgContainWidth = $(img).width();

    var bgContainHeight = (bgheight*bgContainWidth)/bgwidth;

    var decimal = bgContainHeight.toString().split('.');

    if(decimal[0]>=5)
    {
       bgContainHeight = Math.ceil(bgContainHeight);
    }
    else
    {
       bgContainHeight = Math.floor(bgContainHeight);
    }

    alert('bg Contain width = ' + bgContainWidth
           + ',bg Contain Height = ' + bgContainHeight);

}

$('#get').click(function () {
   get('#img');
});

See demo fiddle : http://jsfiddle.net/c4yHf/1/

Upvotes: 1

Dpeif
Dpeif

Reputation: 531

I think the flaw with this plan is that the background-image isn't really part of the DOM when the page is loaded. When you query .css('background-size') you'll return the CSS rule value (i.e. key:value) that is assigned to that rule's key.

So if i have a div with a background of #000 and i ask jQuery to return $('div').css('background') it'll return the value of #000.

Since you're using the container to scale a background image, to squeeze it to new dimensions, your value for .css('background-size') will never be a computed value like "100px 500px". It will probably be "auto". Also, the property of background-size doesn't have an attribute of width so .css('background-size').width() won't return a value in the jQuery you have above.

The only solution I can think of is to use JS to find the initial dimensions of the image, then the final dimensions of it's container after the page renders, and compute the ratio between the two using math and if-else statements.

Example:

IMG original dimensions: 1000px x 400px
container's dimensions after page renders: 600px x 200px

// Compare the ratio of height / height and width / width
widthRatio = .6
heightRatio = .5

// image should scale proportionally, so it must scale to the smallest ratio
// e.g. if it needs to be 50% as tall, it has to be 50% as wide, even though
// it could fit set at 60% its original width

// so multiply ratio (.5) by original dimensions of image (1000px x 400px)
newImgBgDimensions = 500px x 200px

Upvotes: 3

Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

  function getheightwidth(id) {
        var element = document.getElementById(id);
        if (element && element.tagName.toLowerCase() == 'img') {
            return {
                width: element.width,
                height: element.height
            };
        }

    }

    <img id="imageid" src="......jpg" alt="" onclick="getheightwidth(this.id)"/>

     var dimensions= getheightwidth();
    alert("Width is " + dimensions.width +"Height is "+ dimensions.height); 

This should solve your problem :)

Upvotes: 0

bumerang
bumerang

Reputation: 1846

Actualy You are looking for size, of the container (<div id="img">) not an image. If You will get the container dimensions You will get the size of the image inside it ( it's background ). I will give You jQuery solution:

$(document).ready(function(){
    alert('width: ' + $('#img').width() +'; height: ' +  $('#img').height() );
})

You can also check if the container size is bigger than the oryginal image size.

Upvotes: -1

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can not find the height width background image.there is no way that css can find the properties like height width of background images.what you can do is load the images using javascript or jquery and then getting height/width of those images.

Upvotes: 0

Zero Cool
Zero Cool

Reputation: 144

window.onload = function() {

    var imageSrc = document
                    .getElementById('hello')
                     .style
                      .backgroundImage
                       .replace(/url\((['"])?(.*?)\1\)/gi, '$2')
                        .split(',')[0];

    // I just broke it up on newlines for readability        

    var image = new Image();
    image.src = imageSrc;

    var width = image.width,
        height = image.height;

    alert('width =' + width + ', height = ' + height)  

}

Upvotes: 0

Related Questions