Search code examples
jqueryconsolidation

Condensing repeating JQuery code


I have a page that has a large image on it with a number of thumbnails. When you mouse over a thumbnail the main image changes to the image you have just rolled your mouse over. The problem is the more thumbnails I have, the more repeated code I have. How could I reduce it?

The Jquery code is as follows.

<script type="text/javascript">  
    $('#thumb1')
.mouseover(function(){  
$('#big_img').fadeOut('slow', function(){  
$('#big_img').attr('src', '0001.jpg');  
$('#big_img').fadeIn('slow');  
            });  
        });  
    $('#thumb2')  
        .mouseover(function(){  
            $('#big_img').fadeOut('slow', function(){  
                $('#big_img').attr('src', 'p_0002.jpg');  
                $('#big_img').fadeIn('slow');  
            });  
        });  
     $('#thumb3')  
        .mouseover(function(){  
    $('#big_img').fadeOut('slow', function(){  
                $('#big_img').attr('src', '_img/p_0003.jpg');  
                $('#big_img').fadeIn('slow');  
            });  
        });  
     $('#thumb4')  
        .mouseover(function(){  
            $('#big_img').fadeOut('slow', function(){  
                $('#big_img').attr('src', '0004.jpg');  
                $('#big_img').fadeIn('slow');  
            });  
        });  
</script>

#big_img = the ID of the full size image

#thumb1, #thumb2, #thumb3, #thumb4 = The ID's of the thumbnails

The main code for the page is PHP if that helps.


Solution

  • First of all, you should modify your code so that each thumbnail has an easy to find 'class'.

    Assuming you have

    <img id="thumb1" scr=""/>
    <img id="thumb2" scr=""/>
    ..
    

    your html should look like

    <img id="thumb1" class='thumb' scr=""/>
    <img id="thumb2" class='thumb' scr=""/>
    ..
    

    Second you should make sure that you have an identifiable pattern between all you thumbnails and their big image counterpart. In your code we have

    0001.jpg
    p_0002.jpg
    _img/p_0003.jpg
    0004.jpg
    

    what is your organization for your files ?

    Let's imagine for now that the thumbnails have the same src as the bug images

    The jQuery code would be shrinked to :

    $('.thumb').mouseover(function(){
    
        var thumb_src = $(this).attr('src');
    
        // ==> add code here to transform thumb_src into the big_img src
    
        $('#big_img').fadeOut('slow', function(){
            $('#big_img').attr('src', thumb_src);
            $('#big_img').fadeIn('slow');
        });
    });
    

    This code should work and just waits for the algorithm that transforms the src of the thumb into the src of the big image

    I hope this will help you Jerome Wagner