1

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.

1 Answer 1

6

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');
});
Sign up to request clarification or add additional context in comments.

2 Comments

HA! It worked!! I can't believe this thing has been kicking my a** for the last two hours! So basically I'd need to bind the click events for all generated divs that can be clicked upon?
You can bind event to your parent element where you append e.g. '#container'. jQuery(document) could be jQuery('#container')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.