Reputation: 543
I'm working on a project combining HTML
and JQuery
. There is an event that couses a replace of a div
with a new div
from an external html file(using load('some.html #someDiv'
)).
So far so good, the problem begins when I'm trying to listen to an event(click
if it matters)of an img that is a part of the new div
.
I'm guessing it has something to do with the fact that I didn't defined the click event of that img in the ready
function because the image warn't exist at the time in the page.
Anyway nothing I could think of to solve this didn't seem to work..Thanks for the helpers
Upvotes: 1
Views: 794
Reputation: 7352
Use .on()
http://api.jquery.com/on/
$(document).on('click','.someNevDiv img', function() {
// Code on click
});
With your code :
$("#newDiv").click(function() { onNewDivClicked(); });
Should be :
$(document).on('click', '#newDiv', function() {
onNewDivClicked();
});
Upvotes: 1
Reputation: 89
Try binding the click after you've added the element:
i.e. according to jquery docs here: http://api.jquery.com/load/#callback-function
You should be able to do something like this:
$('#result').load('ajax/test.html', function() {
$('#result img').bind( 'click', function(){
alert( 'this is fired on a click event on images inside of #result' );
});
});
Upvotes: 0
Reputation: 44740
use .on()
$(document).on('click','#newDiv img',function(){
});
Upvotes: 3