Posted by: Praveen | July 17, 2010

Simple trick to set the max-width for an image (javascript)

If you would like to set the maximum width for an image on a webpage, you can use the “max-width” attribute of style(CSS). But this attribute is supported by FireFox and some other browsers but not Internet Explorer (IE). The following code snippet shows you how to achieve the same thing as “max-width” for Internet Explorer using javascript.

ASP.NET

<asp:Image runat=”server” ID=”Image1″  ImageUrl=”test.jpg” style=”max-width:150px;”/>

HTML

<img id=”Image1″ src=”test.jpg” style=”max-width:150px;” />

JavaScript Code

var Img = document.getElementById(‘<%=Image1.ClientID %>’);
//use document.getElementById(‘Image1′); for HTML
if (Img.width > 150) {
Img.style.width = 150;
}

Advertisement

Responses

  1. very cool & good js tip, thank you very much for sharing.

  2. The problem with resizing images is that it takes time to load big images, thus the resetting of the width does not render properly.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.