views:

316

answers:

5

I've an img element with dynamically changing image. I always want to show this image in its full dimension.

So, I think, I've to dynamically change width and height attributes in img tag.

How can I do this in php or javascript?

+11  A: 

Just leaving off the width and height attributes (and styles) should do. If you need to know it afterwards you can grab it from the computed CSS.

Plynx
+1 you can additionally use `max-width` and `max-height` to prevent too large images from breaking the layout.
Pekka
Wouldn't omitting width and height affect xhtml validation?
understack
@understack, No, leaving out the `alt` tag would generate a warning, but neither `height` nor `width` are required by the spec. Though they're useful for the browser to know in advance, to draw the page according to the proper dimensions without having to first wait for the image to load (and potentially trigger a re-draw).
David Thomas
+1  A: 

Couldn't you do without the width and height dimensions? As far as I've seen if you don't define the width and height the browser displays the entire full size image. Most modern browsers that is.

JonnyLitt
+1  A: 

Assuming that you care about alt, height, and width attributes (you should), reading the image properties from a javascript array may be a good fit for you. Here's an example in jQuery inserting a random image, you could swap the random image logic out for any kind of slideshow, etc that you'd like for rendering.

$(document).ready(function() {

  var imageArray = new Array ();
  imageArray[0] = new Array ( "jungle.jpg",   "http://rmportal.net", "Jungle", "400", "300");
  imageArray[1] = new Array ( "mountain.jpg", "http://rmportal.net", "Mountain" , "350", "290");
  imageArray[2] = new Array ( "ocean.jpg",    "http://rmportal.net", "Ocean" , "442", "530");

  var max = imageArray.length;
  var num = Math.floor((Math.random() * max));

  var hstring = "<a href='" + imageArray[num][1] + "'><img src='" + imageArray[num][0] + "' alt='" + imageArray[num][2] +  "' height='" imageArray[num][3] +  "' width='" + imageArray[num][4] + "' /></a>"

  $('#my-image').html(hstring);

});
siebo
+1  A: 

If you’d prefer to keep the width and height attributes in your HTML, then in PHP you want the getimagesize method in the GD library.

Paul D. Waite
A: 

If the page loads with the image’s width and height included as attributes in the source, use removeAttribute('width') and 'height' the first time you change its source.

If you don’t want the page to ‘collapse’ during a slow download, preload the image and change the src after img.complete is true, which is right away if it is cached, or after the image onload fires.

kennebec