Dynamic Image/Text Wrapping

Update 01/02/2010: In hindsight I should have just used JQuery to check that the page had been loaded, e.g:


$(document).ready(function(){
	$('img.wrap').each(function() {
		var img_width = $(this).attr('width');
		if(img_width>=375) {
			$('#content').style.clear='left';
		}
	});
})

A couple of months ago I encountered an issue with one of the sites I was developing, www.howdenparkcentre.co.uk. The basic page template for the main content area for most pages includes a primary image, title, sub-title and main text. Due to the way the websites columns are percentage based, i.e. they flex depending on browser resolution, there was an issue where sometimes the customer wanted the text to wrap round the image if the image was portrait, or to drop below if it was landscape. Otherwise there was a risk of text running too narrowly along the side of wider images. Due to all of the websites pages being content managed, and potentially the images being very different dimensions I needed to put in a fix for this.

Below shows the HTML code that calls the JavaScript function.

HTML

<body onLoad="checkImage('ImageId','TextContainerId');">

*Please note after having tested the onLoad option on the actual image (which would have been preferable) it being clear this caused further issues. Due to the way images are cached for the second and subsequent visits to a page the JavaScript would not work as often the image had finished loading (due to it being cached) before the text had even been rendered, which meant the code was not executed properly. Therefore the body onload was required

JavaScript:

function checkImage(imageId,textId) {
	if(document.getElementById(imageId) && document.getElementById(textId)) {
		var id = document.getElementById(imageId);
		if(id.width>=375) {
			var textShift = document.getElementById(textId);
			textShift.style.clear='left';
		}
	}
}

The above code checks if the image is equal or wider than 375px, and if so sets the text container to clear left.

blog comments powered by Disqus