Click to enlarge is a common feature on many sites nowadays. And while it may seem like a trivial feature to add to your website, just try it, and then try it on every browser and screen size, and you'll soon find that you're better off forgetting the whole thing and using some 3rd party library instead. Which is why I created the following for your coding pleasure.
It is designed to be a simple plug and play file and will work with any image element on any site. Feel free to modify it and improve it in any way that you wish for all of your web projects. And if you find it useful, feel free to send me a kind word or two.
But because actions speak louder than words, here is a quick example of the script in action.
The new image size is calculated based on the current browser dimensions and the original image size. If the original image is large enough, the modal will be created to wrap the image in its entirety. And if the image is larger than the allowable size, it will be sized to fit the max allowable size. Again, feel free to play with these sizes yourself to whatever makes the most sense for your applications.
How to use it
The script is designed to be class-based. That is, you will need to specify a certain class in each element that you wish to target. On load any elements with that class will generate the necessary controls and events. In order to use it, you reference the script as you would any other script.
Then you simply add a class to each element that you wish to target.
<img src="img1.jpg" class="clicktoenlarge" />
<img src="img2.jpg" class="clicktoenlarge" />
And that is essentially it. You'll have a fully functional click to enlarge script that can be used on any website and that will work with any screen size. The full source is down below for your copy and paste pleasure. Feel free to play around with it and use it as you will and if you found it useful also feel free to throw a few kind words my way.
Did you find this article helpful?
Stay up to date with my weekly coding tips!
Walter G. is a software engineer, startup co-founder, former CTO of several tech companies and currently teaches programming for a coding bootcamp. He has been blogging for the past 5 years and is an avid BMX rider, bio-hacker
and performance enthusiast.