devxlogo

Resizing Images on the Fly

Resizing Images on the Fly

Question:
I know that with DHTML, it is possible to resize images using the Onmousover event handler, but the example shown on the Microsoft Dev site involves basically switching between two different images: one of either size instead of actually resizing the actual image. Is there a way to resize without having the Onmouseover display two separate images? For instance, I have an image that when the mouse isn’t over it I want to be at a default 85 x 128 size, but with the mouse on it, I want it to resize to 255 x 384. Is this even possible? Thanks in advance!

Answer:
Microsoft’s document object model can be a little confusing. There are actually three sets of properties that give the width and height of an image, a div, or any other element. Of the three sets, the one that can be used to resize an image is the pair pixelWidth and pixelHeight (note case here, JavaScript is case sensitive). The properties pixelWidth and pixelHeight are below the style object, and are set if the IMG tag sets the width and height of the image explicitly.

It’s easiest to encapsulate resizing into a single function, which I define here as SetSize. SetSize takes four arguments: a pointer to the object in question (I’ll show you how to reference that in a second), the width and height, and a text flag that can be set to one of the following: (“*”,”%”,”#”,””), with these meanings:

“*” (scale) Multiply the dimensions of the object by the scale factors.
“%” (percent) Multiply the dimensions by the scale factors, then divide by 100
“#” (absolute) Set the dimensions to the scale factors.
“” (default) Same as absolute

You would then call the function in whatever event handler you need. Note that the function doesn’t retain any information about the size of the image initially, although you could retain that information with static variables.

See also  Why ChatGPT Is So Important Today

Now, to call the handler so that it doubled the size when you entered into it and restored it when you left, you’d do something similar to the following:

The term “this” is a pointer to the object being passed (it doesn’t necessarily have to be an image, by the way). The parser will know to associate “this” with its enclosing tag, in this case the IMG tag.

A similar solution can be applied to Netscape objects, although there the salient pair is labeled me.width and me.height respectively rather than me.style.pixelWidth and me.style.pixelHeight.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist