views:

108

answers:

1

I am writing a simple image replacement script on a site I am working on and having a bit of trouble.

The code I have at the moment consists of:

$(function() {

  // When a thumbnail is clicked
  $(".zoom_thumbs a").click(function() {

    // Get large image attributes
    var largeImg = $(this).attr("href");
    var largeTitle = $(this).children("img").attr("title");
    var zoomImage = $(".zoom_cnt .zoom img");

    //Change the attributes of the large image
    $(zoomImage).attr({ src: largeImg, alt: largeTitle, title: largeTitle });

    // Once the attributes have been changed,
    // reposition the div containing the image to center it
    var wideWidth = $("#wide").width();
    var imageWidth = $(".zoom_cnt").width();
    var marginLeft = (wideWidth - imageWidth) / 2;
    var wideHeight = $("#content").height();
    var imageHeight = $(".zoom_cnt").height();
    var marginTop = (wideHeight - imageHeight) / 2;
    $(".zoom_cnt").css("left", marginLeft);
    $(".zoom_cnt").css("top", marginTop);

    return false;
  });
});

I have put in some comments to show you what I am doing in each step and what I want to achieve. My problem is I want the reposition of the div containing the image to occur after image attributes have been changed. At the moment it doesn't unless I click the thumbnail again (I take it this is because the image has already been loaded and in is cache?). Is what I am trying to do achievable?

Any help would be greatly appreciated :)

P.S I am aware that once this is done the images are going to be jumping about, but I will be doing hide/show effects once this has been fixed.

+2  A: 

You want to use the load event for the image to trigger execution of the code that depends on the loaded attributes:

//Change the attributes of the large image
$(zoomImage)
  .load(function()
  {
    // Once the attributes have been changed,
    // reposition the div containing the image to center it
    var wideWidth = $("#wide").width();
    var imageWidth = $(".zoom_cnt").width();
    var marginLeft = (wideWidth - imageWidth) / 2;
    var wideHeight = $("#content").height();
    var imageHeight = $(".zoom_cnt").height();
    var marginTop = (wideHeight - imageHeight) / 2;
    $(".zoom_cnt").css("left", marginLeft);
    $(".zoom_cnt").css("top", marginTop);
  })
  .attr({ src: largeImg, alt: largeTitle, title: largeTitle });

There might well be a way to do this using pure CSS as well, but since you didn't specify the structure of the markup you're working with, i can't really speculate on that.

Shog9
Thanks for your help Shog9, but the code you provided doesn't really make sense and does not work:I nested the code you provided within the .click function, but now nothing happens at all. :/
Nevermind... fixed it haha! Thank you