3

I keep the images of my site in Picasa... as we know we can set size of picture like this.

http://lh5.ggpht.com/-i97UI0TXchE/UatpZd-E3tI/AAAAAAAAAFg/HUu-QK63ce0/w900-h0/running-sml.jpg

The part w900-h0 means that, the picture size is: width 900px and the height 0 (auto).

And so I need change this url, (acctualy the part w900-h0) of the image automaticly depending of the viewport of the device, I know that I can make images fluid just set them max-widht:100%; via css, but in that case the picture's size is not getting smaller, and it just visually small.

How can I change the part w900-h0 via java-script, for example when viewport is 480 the url is changed w300-h0 and so on.

Hovhannes Sargsyan
  • 1,063
  • 14
  • 25
  • What have you tried? Which part are you having trouble with i.e. how to calculate the sizes, how to replace the image's `src` property, how to find which images to change...? – Graham Jun 02 '13 at 16:14
  • ok, so my images always in div with class `the-image`, by default the width in the src of the image will be 800 (`w800`), so, when the viewport is smaller than 900, the part of the url (src of the image), `w800` is change to `w400`. – Hovhannes Sargsyan Jun 02 '13 at 16:27

1 Answers1

5

You can use something like this to change image width in document.ready state:

imageWidth = $(window).width();
$("#my_image").attr("src","http://lh5.ggpht.com/-i97UI0TXchE/UatpZd-E3tI/AAAAAAAAAFg/HUu-QK63ce0/w"+imageWidth+"-h0/running-sml.jpg");

Function $(window).resize() can also be helpful to resize dynamicaly.

Update:

If you want to do this for more than one image:

imageWidth = $(window).width();
$(".imageForResize").each(function() {
  $(this).attr("src", $(this).attr('src').replace('w900-h0', 'w'+imageWidth+'-h0'));
});

Example on JSFiddle

yarl
  • 3,107
  • 1
  • 22
  • 28