Biltong
Biltong

Reputation: 11

Resize image as window resizes using Javascript - not working in Chrome

I'm using the following javascript to resize image as window resizes which works correctly in all browsers except Chrome:

<!DOCTYPE html>
<html>
<head>
<style>
* {
  padding: 0;
  margin: 0;
}
.fit {
  max-width: 100%;
  max-height: 100%;
}
.center {
  display: block;
  margin: auto;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="JavaScript">
function set_body_height()
{
    var wh = $(window).height();
    $('body').attr('style', 'height:' + wh + 'px;');
}
$(document).ready(function() {
    set_body_height();
    $(window).bind('resize', function() { set_body_height(); });
});
</script>
</head>
<body>
<img id="the_pic" class="center fit" src="pic.jpg" >    
</body>
</html>

The problem with Chrome is that the image does not resize to fit the window size when the page first loads but when you resize the browser window after it loaded, the image then correctly resizes to the resized browser window.

Try clicking on http://www.mnhscs.com/christmas

Oddly this problem does not occur everytime the page is loaded in Chrome. Sometimes the image resizes correctly.

Upvotes: 1

Views: 1202

Answers (3)

wwwmarty
wwwmarty

Reputation: 858

$(window).bind('load resize', function() { set_body_height(); });

A few words of explanation, as requested.

As described in other answers, set_body_height should be called from the onLoad event initially, and then listen for resize events. Since document.ready() is fired first, you can bind both events to the same handler, as shown.

Seemed self explanatory.

Upvotes: 0

Kami
Kami

Reputation: 19407

As @Jazzepi pointed out the javascript might not be running as expected in some instances.

However, there is also a CSS only option for applying 100% window height - vh.

.fit {
  height: 100vh;
}

This will ensure the element resizes to the correct height. The vh suffix applies a percentage of the viewer height to the element - 100 in this instance.

Fiddle : http://jsfiddle.net/87avhd4v/1/

Upvotes: 0

Jazzepi
Jazzepi

Reputation: 5480

Because you're using $(document).ready you have a race condition on your image loading. Sometimes the image will be done loading before your sizing function is called because .ready() only waits for the dom to be done, not for the images to load. You need to use document.load() which will wait for the images to load as well. The reason you're seeing this in Chrome only is because it's blazing fast :)

Official way to ask jQuery wait for all images to load before executing something

Make sure when you're testing in chrome you turn off your cache. I would not be surprised if the image being cached masked the problem, because the image would load as quickly as the DOM does.

Disabling Chrome cache for website development

Upvotes: 1

Related Questions