0

I am working on a prototype of a project in which I need to adjust the look and feel of site content according to the browser window size.

Now for the prototype I am using a sample image and I want to adjust the height and width of the image as per window's height and width.

Here's the code that I am using:

$(window).resize(function() {
   document.write("<img src='sample_image.jpg' border='0' height='"+window.innerHeight+"' width='"+window.innerWidth+"'>");
});

The above code doesn't work properly. I want to dynamically change the image height and width as user resizes the window. I also tried implementing this solution. But that didn't work either. Any ideas how can I solve this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
skos
  • 4,102
  • 8
  • 36
  • 59
  • 1
    Couldn't responsive design be the solution, instead of javascript ? Just asking :) – Clement Herreman May 07 '12 at 10:23
  • Well I managed to implement this in Flash, but I want to develop it for non-Flash browsers or for iPhone/iPads. Hence I am trying to see if its possible in javascript – skos May 07 '12 at 10:28

3 Answers3

1

Well, since this is needed for testing purposes only, and it seems that you use jQuery, try this code:

<img src="sample_image.jpg" border='0' height="1" width="1" style="display: block;">

<script>
    var resize = function() {
        $("img").width($(window).width()).height($(window).height());            
    };
    $(window).resize(function() {
       resize();
    });
    resize();
</script>​

DEMO: http://jsfiddle.net/GvRJ7/

Otherwise, myself and other guys here strongly recommend you using good HTML/CSS markup to make your design fit any resolution.

VisioN
  • 143,310
  • 32
  • 282
  • 281
0

Instead of window.innerHeight and window.innerWidth you can try using percentage.That Will Resize your image accordingly to windows height andwidth.

document.write("<img src='sample_image.jpg' border='0' height='"70%"' width='"70%"'>");
vishnu
  • 869
  • 1
  • 16
  • 25
0

Think of how often window.resize() fires (if you have any doubt, console.log() it). Only inexpensive operations should be performed inside it, like incrementing a counter, or calculating a position.

In your particular case, I think a 100% width/height image will work using just CSS (or CSS generated with JavaScript if needed). Of course, this will look bad as the image gets beyond its real size, and waste bandwidth when it is below its real size, but it will have the equivalent effect to your code at a fraction of the expense.

As a side note, document.write() should rarely be used. Use DOM manipulation functions instead.

Tim M.
  • 53,671
  • 14
  • 120
  • 163