NaN
NaN

Reputation: 1306

Change image on click with jQuery

Sorry about the vague title but I'm not really sure how to describe this.

What I want to do is onclick, change the image. Here is that portion of the code.

Can someone tell me if this is possible? I don't see a way to do this because I'm not sure how to reference the anchor tag.

$(document.createElement('a'))
  .attr('href', '#')
  .html('<img src="myimage.jpg" />')
  .click( function( e ){
    // When the user clicks the anchor tag above, I want to replace the current
    // image (myimage.jpg) with another one.
  }

Upvotes: 0

Views: 121

Answers (5)

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

Use this simple one

$('img').click(function () {
 $(this).attr('src', 'src/to/new/file.png');
}

If you want to change the image when click is over the a. Then use

$('a').click( function () {

instead of the image one.

That will change the src attribute of the current image.

Here is a working fiddle for this :)

http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

You will se when the mouse is hovered over the image, it changes. You can use click instead of hover. That should work. And don't create a if you have to disable it using href="#".

If you want a cursor of pointer use cursor: pointer in CSS or use

$(this).css('cursor', 'pointer');

Upvotes: 1

Xaver
Xaver

Reputation: 11712

//create node
$('<a>', {
   'href': '#',
   'src': 'myimage.jpg'
})

//add it to the body
.appendTo('body')

//add envent
.on('click', function(){
   $(this).attr('src', 'otherimage.jpg');

   //prevent to jump to the top of the page caused by the '#'
   return false;
});

Upvotes: 1

Steve
Steve

Reputation: 8640

$(document.createElement('a'))
  .attr('href', '#')
  .html('<img src="myimage.jpg" />')
  .click( function( e ){
      $(this).find('img').attr('src','myNewImage.jpg');
  });
}

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50808

The easiest way is just to give the image a class, like, "myImg", and use the .on() method to bind to dynamically created elements

$(document).on('click', '.myImg', function(){
    //$(this) refers to the image that we clicked
    $(this).prop('src', 'http://my-domain.com/path/to/my/new-image.jpg');
});

This binds the event to the document, and anytime an image with the class of "myImg" is clicked, it will replace the image.

Upvotes: 1

Brian
Brian

Reputation: 7654

Assuming you want to retain the state of the code in which it is written (which is horrible), e.currentTarget is a reference to the element that is being clicked. You can use that to repeat your (discouraged) .html() procedure with another image URL.

$(document.createElement('a'))
    .attr('href', '#')
    .html('<img src="myimage.jpg" />')
    .click( function( e ){
        $(e.currentTarget).html('<img src="myimage2.jpg" />');
    });

Upvotes: 1

Related Questions