Rickstar
Rickstar

Reputation: 6189

Add a new image in jquery and make it clickable

I am trying to add an image in jquery and then make it clickable I have maked the following code below but it does not work.

It adds the images but it will not make it clickable.

 $(".HeaderGifs").click(function() { 
 alert("It Works");
 }); 


 $("#show_images").val()).append("<img class='HeaderGifs' src='images/text.jpg'></img>");

Upvotes: 1

Views: 10475

Answers (4)

amashaa
amashaa

Reputation: 1

To make only image clickable use the code below:

$('.HeaderGifs').on('click',"img",function() {....}

Upvotes: 0

treeface
treeface

Reputation: 13341

If you want an element with a particular class to always respond to the click event, you need to use one of jQuery's methods to do this. When you just use click(), you're basically telling jQuery to only apply that event listener to elements with that class right now, instead of for every element present and future. For this purpose, jQuery has the on() method:

$('.HeaderGifs').on('click', function() {....}

http://api.jquery.com/on/

Edit: I should also mention the delegate() method, just in case you find more value in doing it this way:

http://api.jquery.com/delegate/

Upvotes: 5

Alpesh
Alpesh

Reputation: 5405

For binding to the elements occuring or inserted in the future (like in your case you are inserting whole img tag later ) you have to use .live() or .delegate() functions.

The detailed documentation for both are available below -

.live()

.delegate()

Upvotes: 0

Moin Zaman
Moin Zaman

Reputation: 25455

use .live() to add event handlers to elements that you create after page load

Upvotes: 0

Related Questions