Toby Behan
Toby Behan

Reputation: 137

jQuery Fade in and Fade out image with Ajax

I have a simple job I am trying to do. I have a series of thumbnails and a main picture.

http://activate5.info/index.php#portfolio

Upon clicking a thumbnail, I need to do an ajax call to look up an array, which returns a new image and text info. I then need to fade the main picture out, and replace it with the new information which comes from the ajax call.

It is working, but its jerky. What is happening (I think) is the fadeout is smooth, but the fade IN jerks because the image is new content to the page, and it displays in a jerky way, like when pictures normally load on a page.

I'd like it smooth - so ideally, I need some kind of alert / trigger for when the image has totally loaded, before I fade the image in. I'm sure it's a simple answer - but would appreciate help.

I've put the fadeout / fadein stuff in the 'success' portion of the ajax call...

$.ajax({
 url: 'resources/portfolio/ajax_portfolio_data.php',
 data: { client: clientCode,
          slide: slideNumber
       },
 success: function(data) {
      $('#slide'+slideNumber+'_portfolio').fadeOut('slow',function(){
         $('#slide'+slideNumber+'_portfolio').html($.parseJSON(data));
         $('#slide'+slideNumber+'_portfolio').fadeIn('slow');
      }); 
  }
});

I really don't want to preload ALL available images, as that would slow an already large page down more - anyone have a better way to do this?

Example of what is returned by the PHP file for the (data) is:

$html = "<div class='slideMainImage'><img src='" 
   . $portfolio[$slide][$client]['image'] . "' /></div>";
$html .= "<p>" . $portfolio[$slide][$client]['text'] . "</p>";
echo json_encode($html);

Thanks in advance.

Upvotes: 1

Views: 1058

Answers (1)

Mark
Mark

Reputation: 19977

You could add the image on ajax success, hide it and attach an onload event handler. When it's loaded, you execute the code that currently executes on success.

Note that the effect may be more smooth that way, but the overall process is slower because the effect only starts when the image is fully loaded.

Upvotes: 1

Related Questions