Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery crossfade without a plugin

Tags:

jquery

image

fade

a lot of stuff here pointing to plugins to do crossfades and stuff, but none really fit my needs.

i have 2 things on my page: A large image, a div containing 3 or four small thumbnails

when a thumbnail is clicked it reads in the src and changes the main images source to the new image.

how do i get it to fade one in while the other fades out ( so it does not go to nothing before fading in the new image)

heres my code:

$('.TnImage').live('click', function() {
        var newImage = $(this).attr('src');
        var oldImage = $('.mainImage').attr('src')
        $('.mainImage').fadeOut('slow');
        $('.mainImage').attr('src', newImage).fadeIn('slow');
    });

Just for clarification why i dont want to use existing plug-ins, is that most require you to know the list of images to be loaded in before hand, the thumbnail images are retrived from a mysql database through php, and i'd rather not have to make 2 lists one for the thumbnails and 1 for the main images then hiding all but the one main div with the image in i want showing.

i have had a look a cycle plugin but i'd prefewr not to use it, I know people keep going on about not reinventing the wheel, but if i keep using plugins to do stuff, i'm never going to learn the nuts and bolts of how jquery works. i used to use the excellent IMAGESWITCH but does not work with jquery 1.4.3, and i need this version for its's html data() and so by relieing on this previously, i am now stuck so why i have asked a way of doing this without using plugins.

like image 942
Dizzy Bryan High Avatar asked Apr 14 '11 14:04

Dizzy Bryan High


2 Answers

jQuery cycle will do this, but it is a plugin.

In order to do this without a plugin, you could load the images and then hide all but the first. When an thumbnail is clicked, you then fade out the selected image. I would add a css class to the first image to make it easier to do. I'd also give an id to each image to reference them. Use CSS to place them on top of each other. In your thumbnail image tag, you would need some sort of reference to the big image too.

$('.TnImage').live('click', function() {
    $('.selected').fadeOut(500, function(){
        $(this).removeClass('selected');
    });
    $('#'+$(this).attr('imgidref')).delay(250).fadeIn('slow').addClass('selected');
});

I know this is a crude example, but it should cover the basic principles.

like image 138
Scott Harwell Avatar answered Sep 20 '22 08:09

Scott Harwell


If I understand the question (aside from your desire to avoid plugins :) jQuery Cycle should do exactly what you want. Use the fade transition combined with the pager option.

http://jsfiddle.net/mattball/xM3cC/

like image 43
Matt Ball Avatar answered Sep 18 '22 08:09

Matt Ball