Reputation: 303
I'm having an issue with jQuery in that when I receive the html response from an ajax call and prepend it to a div, a div from the received html won't call another function from my external javascript file.
In my index.php page, I have referenced an external javascript file:
<script src="functions/functions.js" type="text/javascript"></script>
The above script contains the following:
jQuery(document).ready(function()
{
$(".active").on('click', function()
{
jQuery.get('../ajax/file.php', function(data) {
jQuery('#container').prepend(data);
});
})
jQuery("#mydiv").on('click', function(event)
{
alert('clicked');
});
});
When a div with the class 'active' is clicked upon, the file.php is called - all it does is output the div with the id of 'mydiv'
<div id="mydiv"></div>
Now when I click on the 'mydiv' div, it doesn't call the function from the functions.js file. I've moved the above div outside of the ajax call directly into the index.php file which executes the function fine, but as I say, if it's generated and appended via the ajax call, it doesn't want to work.
Upvotes: 1
Views: 491
Reputation: 148150
Bind the click event on document with #mydiv filter so that when html containing element with id mydiv added event is attached dynamically.
jQuery(document).on('click', "#mydiv", function(event)
{
alert('clicked');
});
Or if the response is added to '#container' then you can bind event to '#container',
jQuery('#container').on('click', "#mydiv", function(event)
{
alert('clicked');
});
Upvotes: 6