How to: enlarge images on click using CSS and JavaScript

∞ Fri, 27 Apr 2012 · Comments

Instead of using a lightbox script to display enlarged versions of embedded images, I decided that there was a better solution, for my own needs anyway: images should simply expand to their full size on click. So, I sat down today to figure out how to do that, and arrived at a solution that I feel is good enough for me to replace the otherwise excellent fancyBox with. If you want a quick demonstration of what I mean, head over to my PSDs page – clicking on any image will enlarge it, or you can even click on a special link to quickly toggle all images between regular and full size.

Here’s how to do it.

Prerequisites

Of course, this solution may or may not be the right one for you. If you have small thumbnails that you want to link to the full image, lightbox scripts are probably the way to go; if you have images that are exactly the content width, you won’t need anything special at all. This solution – enlarging images on click – is suited for those tasks where the full image is displayed, but with max-width: 100% and height: auto to fit in with the content. Basically, both the <img> and the <a> wrapped around it should point to the same file:

<a href="image.png"><img src="image.png" /></a>

The CSS

Very easy – an additional class removes the restriction on max-width. This is all you need to put in your stylesheet:

img {
    height: auto;
    max-width: 100%;
}
img.expanded {
    max-width: none;
}

Now, we need to apply the expanded class to the clicked image.

The JavaScript

Place this code snippet somewhere in the <head> section (don’t forget to include jQuery):

$(document).ready(function() {
        var imageLinks = $('a[href$=".png"], a[href$=".jpg"], a[href$=".gif"], a[href$=".bmp"]');
        if (imageLinks.children('img').length) {
            imageLinks.children('img').each(function() {
                var currentTitle = $(this).attr('title');
                $(this).attr('title', currentTitle + ' (click to enlarge image)');
            });
            imageLinks.click(function(e) {
                e.preventDefault();
                $(this).children('img').toggleClass('expanded');
            });
        }
    });

It’s pretty straightforward. First, the script fetches all <a> elements that link to an image file, and then looks for an <img> child element. If it finds one, it appends the “click to enlarge image” text in parentheses to the title attribute, and registers a click handler that prevents the link from firing to instead toggle the expanded class (see CSS) on our <img>.

Animation

Since CSS3 allows for easy animation, let’s make the transition between regular/full size smooth! As the transition property isn’t final yet, we have to add all those pesky vendor prefixes:

img {
    height: auto;
    max-width: 640px;
    -moz-transition: all 1s;
    -ms-transition: all 1s;
    -o-transition: all 1s;
    -webkit-transition: all 1s;
    transition: all 1s;
}
img.expanded {
    max-width: 2000px;
}

If you’re wondering why the max-width values changed… some browsers will not display the animation without pixel values. So, just replace 640px with whatever your content width is, and 2000px with whatever (large) size you anticipate your images to be.

Bonus

To quickly toggle all images (like on my PSDs page), you will need to add such a link into your markup:

<a href="javascript:void(0)" onclick="toggleExpand()">Click here to enlarge all images.</a>
<script type="text/javascript">
function toggleExpand() {
    var expanded = true;
    $('img').each(function() {
        if (!$(this).hasClass('expanded')) {
            expanded = false;
            return false;
        }
    });
    $('a[href$=".png"], a[href$=".jpg"], a[href$=".gif"], a[href$=".bmp"]').children('img').each(function() {
        if (expanded)
            $(this).removeClass('expanded');
        else
            $(this).addClass('expanded');
    });
}
</script>

First, the toggleExpand() function checks if all images have been expanded already. If not, expanded (the variable) is set to false, and the expanded class is applied to all <img> elements in the else statement; otherwise, it is removed from all <img> elements.

That’s it

If you’ve got any questions, or even improvements to my solution, feel free to leave a comment!

  • Vinsha

    Its not work please give better code for enlarged image

    • It definitely works (I’m using it on my PSDs page) so make sure you really included *everything* – correct HTML, CSS and JavaScript (don’t forget jQuery too).

      • joe

        how do you include the jquery? :o

        • Easiest way would be adding in the head- section. This is the version hosted by Google, so you don’t need to download anything. I’m using this myself.

  • Sunny

    Why my picture opens in the same window but on a blank page? I have to click back button on the browser to go back to my website.

    • Sounds like the JavaScript is not working. Can you go over to my test page http://livven.me/psds/ and see if it works there?

    • Vaibhav Parikh

      Hi sunny ,Did you find the solution…?

      I am facing the same issue

  • cs

    Thanks…….working gr8

  • Thomas

    Powerfull!

  • This works on Windows 7 but when I tried it today on a PC running XP as its operating system, the flash player plays above the image when enlarged, I used the latest version of Google Chrome on both, I think it could be the flash player version though. Could you modify the code so it pauses any flash animations when enlarged?

    • Sorry I’m not familiar with Flash. I guess you could try and set the z-index of the image to an arbitrary high number but I’m not sure if it’s able to override embedded Flash content.

  • Is there one to enlarge it onspot?

    • You can of course always try traditional lightbox solutions such as fancyBox, which is linked at the top of the article.

  • Ava Burnham

    This isn’t quite working for me and I’m not sure why. What is the child element?

    Also one example of an image I include is:

    Is that wrong? Should I not have the width and height set in this way in order for your code to work? Or am I just somehow missing the child element?

    Thanks!!

    • Replace width with max-width and use height: auto and it should work.

      This solution is really intended for scenarios where the width is restricted by an outer element, such as a div, though, so usually you’d simply use max-width: 100% on the image and it will automatically grow to the maximum width as allowed by the outer element. Here’s a simple example http://pastebin.com/ksy1hDTR

      • kkgfhgh

        fgghgf

  • Megan O

    This isn’t working for me either. Like the comment from years ago, clicking the image opens it on a blank page in the same window (I’m a newbie but I think this means the default override in JS isn’t working).. I’ve checked everything, my j query is properly linked. I even tried using the j query link posted below (version 1.7.2) and the newest version. I’m positive my HTML and CSS are correct.

    Is there a reason why this wouldn’t work before making the page live in FTP? Don’t see why that would be the case, but I’ve exhausted my options.

    I’ve changed nothing from this code, except of course the img src

    • Matt

      I figured out the problem. He stated above to put the javascript in the section. I got the same problem you did doing that, but when I moved it into the it worked like a charm! Thanks for the neat script Livven!

  • Guest

    Wouldn’t it be much easier to just use the image itself as the link and just remove the first class and add the new one.

    $(“img”).click(function(){
    var className = $(this).attr(‘class’);
    if (className==’image’) {
    $(this).removeClass(‘image’);
    $(this).addClass(‘expanded’);
    } else {
    $(this).removeClass(‘image’);
    $(this).addClass(‘expanded’);
    }
    });

  • Chris Ryan

    Wouldn’t it be much easier to just use the image itself as the link, and when clicking the link toggle the class.

    $(“img”).click(function(){
    $(this).toggleClass(‘expanded’);
    });

  • Reseda Mickey

    is it possible for the original image size to be set by the page’s html?
    I want any image, no matter what size it has been set by the html on the page, to expand to the image file’s 100% size when clicked.

    (ps it is useful that I currently can PREVENT every image on the page from reacting by simply designating a width = 20%px or whatever width I want.)

    img {
    height: auto;
    max-width: NUMBER OF PIXELS INDICATED IN THE HTML ON THE PAGE;
    }

    img.expanded {
    max-width: 100%;
    }

  • Ian

    Thanks man, best solution I found