views:

38

answers:

3

Is there a way to find out the width and height of the follow image with Jquery?

<div id="imgBox"><img id="imgID" src="images/koala.gif" /></div>

Then pass it into CSS?

<style type="text/css">
   #imgBox, #imgBox img { width:imageWidth; height:imageHeight }
</style>

I'm guessing...

<script type="text/javascript">
    $(document).ready(function(){
       var imageWidth = $("#imgBox").width();
       var imgHeight = $("#imgID").height();        
    });
</script>
A: 

You could do

$(function() {
    var imgSrc = $('#imgId').attr('src');        
    var image = new Image();
    var width, height;       
    image.onload = function() {
        width = image.width;
        height = image.height;
    };
    image.src = imgSrc;        

});

You could then write the CSS with JavaScript.

$('<style />', {
    html: '#imgBox, #imgBox img { width:' + width + 'px; height:' + height + 'px }',
    type: 'text/css'
}).appendTo('head');

But, why do you need to do this?

alex
I think you're forgetting that images may not be cached ;)
Nick Craver
@Nick I'm not aware that is a problem! Are you saying this code will fail if the user has turned off their cache?
alex
@alex - Images take time to load, in your code above unless it's already cached, the values will be 0 :)
Nick Craver
@Nick Oh yep, of course! Whoops, will make an edit :)
alex
A: 

you can do this way , but can you tell why do you want to overwrite css.

        var $imgId = $('#imgId');
        var h = $imgId.height();
        var w = $imgId.width();

do all your math here

 $imgId.css('height', yourcalculatedheight);
 $imgId.css('width', yourcalculatedweight);

you can parse the dom and change it dynimically instead of going and changing the css which might be good approach

gov
let me know what excatly you want to do for that image , i can post the code.
gov
4 spaces before a line formats as code. `ctr-k` does this on a selection.
Peter Ajtai
+1  A: 

Why don't you set the CSS dynamically?

$(document).ready(function(){
   // make sure img is loaded:
   $("#imgID").load(function() {
       var $this = $(this);

         // Set dimensions of box  using dimensions of img
       $("#imgBox").css("width",  $this.width());      
       $("#imgBox").css("height", $this.height());
   });       
});

You can ofcourse add to the values of $this.width() and $this.height() when you set the css for #imgBox if you need to for aesthetic reasons... let's say if you have a background image in #imgBox you want to show the edges of.

Peter Ajtai
slowman21
@slowman21 - You're welcome ;)
Peter Ajtai