user1471980
user1471980

Reputation: 10646

click on an image to load another image in jquery

I have an image displaying using the jquery. When mouse over to that image, I like the mouse to change to be clickable and when clicked, I like to load another image. This is my code and not working. Any ideas?

html code:

jquery code:

$("#div1").click(function () {
    var img_cpu = "http://192.168.101.1/cpu.png";
    var myImage = new Image();
    $(myImage).load(function () {
        $("#div2").html(myImage)    
    }).error(function () {
        $('#div2').hide();
    })
    .attr('src', img_cpu)
});

Upvotes: 0

Views: 103

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

some issues occurred

  • you created a new image var myImage = new Image(); but you didn't specified a src later (so load event never triggers)

  • myImage32 is not defined anywhere in your code

furthermore be sure that cpu.png

  • is inside the same folder
  • has minimum permission (644) to be viewed
  • is not already cached, otherwise load event could never occur: in this case you should check for complete property and trigger the handler defined for load event (see snippet below)

 $(myImage).one('load', function () {   /* use one() */
     $("#div2").html(myImage32)    
 })
 .attr('src', img_cpu);

 if (!!myImage.complete) $(myImage).trigger('load');

Upvotes: 2

Paul Richter
Paul Richter

Reputation: 11082

Right off the bat, it looks like you're forgetting to put the URL of the image in your load function. It should look something like .load('url/to/image/', function() ...

Upvotes: 1

Related Questions