Supersimple zoom script, but only big images will zoom out again. Why?


I was not happy with the zoom scripts that I found on the net, so I wrote one myself, or one that simulates it. It has become an extremely simple one, and can be seen in action here (function toggleZoom). Click the images to zoom in and click to zoom out again.

However, only the images with an initial width of >= 100 pixels will zoom out again. The ones width an initial width of < 100 (nrs. 4, 5 and 7) won’t. Why is that, and how do I solve it?

The problem is happening because you are comparing strings, not numbers.

Here’s the function that you’re running.

Where within toggleZoom imgCSS is the style of the image.

When you check (imgCSS < wPre) where wPre is the string value ‘164’, the script is comparing two strings to see if “82px” is less than “164”. Since 8 is less than 1, it’s true that in terms of string value, “82px” is less than “164”

You should instead extract the number from the CSS style, and supply the function with numbers instead of strings.

toggleZoom(‘img-stepper’, 82, 164, 125, 250);

if (Number(imgCSS.width.replace(‘px’, ‘’)) < wPre) would end up comparing two numbers.

Thanks, Paul!

Although if (Number(imgCSS.replace(‘px’, ‘’)) < wPre) had to be: if (Number(imgCSS.width.replace(‘px’, ‘’)) > wPre), that made sense and indeed solved the matter.

One more question: where could I find a good (free or not too expensive) online JS course for intermediate students? I did the beginners course at W3 Schools, plus the DHTML chapter, and passed the test with good grades, but cannot find a good continuation. A book will do as well. Would you know?