tags:

views:

172

answers:

3

I'm appending a table row with an image that when you click it, it fires an event. However it looks like you can't add a 'clickable' image dynamically.

all the previous rows with images are identified by their class attribute when clicked (they loaded with the page).

What I want to avoid is using the live event and making a seperate function, I just want it to click like all the others :(

So the question is, how do I add an event that just makes the existing (already being used) function identify the class of the dynamically added image when clicked...?

+1  A: 

Assuming you have a named function you want to apply when adding new images:

function doSomeMagicThing() { //handle image }

You can wrap your img html, like:

//work now on $newImage, which is a jquery element containing your new image.
var $newImage = $('<img src="some_path.png" />');

//Remember it is not yet in your page, so you will have to 
//append it when you are done working with it.
$newImage
    .click(doSomeMagicThing);                        //add click event
    .appendTo($('someSelectorWhereToAppendTo'));     //append it somewhere!
Alex Bagnolini
it's not a named function it's a $(".class").click(function()how do you make a named function in jquery?
jim smith
You don't make it "in jquery". Javascript functions: http://www.w3schools.com/js/js_functions.asp
Alex Bagnolini
A: 

Thanks for your help, but I am completely clueless about jquery and named functions

In the end I created a live event and copied the code from the original function. If anybody knows how I can call one function from both processes it would be most appreciated.

jim smith
A: 

You can make a named function as in any JavaScript:

function myFunc(){

}

In your jQuery code you can then use .click(myFunc). The function myFunc is being passed as a 'callback'. In your old code you have been passing an anonymous function as a callback in the same way, assuming you did something like .click(function(){ }).

A common pitfall is to write accidentally .click(myFunc()), which passes the return value of myFunc as the callback instead of myFunc itself.

You can treat functions as variables for most purposes (they have 'scope' in a similar way, except functions can't be redefined later). You can even create named functions by assigning anonymous ones to variables:

var myFunc = function(){

}

and then you can treat myFunc exactly as you would any other variable.

pjcd