0

I want a click on a thumb to reveal a larger image with a pre-loader and then a fade-in when loading is complete.

I am almost there thanks to this answer - which enables different images to load depending on what thumb is clicked - and this guide which sorts out the loading bit.

Combining the two I have the following script:

 <script type="text/javascript">
    <!--
    $(function () {
        $('img[id^="thumb"]').click(function () {
        $('#loader').show();
        var id = $(this).attr('id').replace('thumb', '');
        var img = new Image();
        $(img).load(function () {
            //$(this).css('display', 'none');
            $(this).hide();
            $('#loader').removeClass('loading').append(this);
            $(this).fadeIn();
        }).attr('src', 'photos/1.jpg');
    }); });

    //-->
    </script>

You will notice at the end that the .attr source is fixed on one image. What I want is that the number before the '.jpg' changes depending on the id of the thumb (they are labelled: 'thumb1', 'thumb2' etc.)

Is there any way of doing this? Much thanks!

ps This answer seems to be close but the problem I have is that the thumb id seems to be too early on in script to be able to use such simple solutions.

Community
  • 1
  • 1
bravokiloecho
  • 1,413
  • 5
  • 22
  • 39
  • I recommend you to have a look at Javascript Closures, that will clear your confusion about "the thumb id seems to be too early on in script to be able to use such simple solutions" – Toni Toni Chopper Nov 29 '11 at 11:43

1 Answers1

2
<script type="text/javascript">

    $(function () {
        $('img[id^="thumb"]').click(function () {
        var thumbId = $(this).attr('id').substring(5); // assuming the id of the thumb is like "thumb1", "thumb2", ...
        $('#loader').show();
        var id = $(this).attr('id').replace('thumb', '');
        var img = new Image();
        $(img).load(function () {
            //$(this).css('display', 'none');
            $(this).hide();
            $('#loader').removeClass('loading').append(this);
            $(this).fadeIn();
        }).attr('src', 'photos/' + thumbId + '.jpg');
    }); });


    </script>
Toni Toni Chopper
  • 1,833
  • 2
  • 20
  • 29