[javascript] How to bind Events on Ajax loaded Content?

I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click event is bound on DOM elements that are not loaded with my AJAX function.

What do I have to change, such that the event will be bound?

My HTML:

<a class="LoadFromAjax" href="someurl">Load Ajax</a>
<div class="appendedContainer"></div>

My JavaScript:

$(".LoadFromAjax").on("click", function(event) {
    event.preventDefault();
    var url = $(this).attr("href"),
        appendedContainer = $(".appendedContainer");

    $.ajax({
    url: url,
    type : 'get',
    complete : function( qXHR, textStatus ) {           
        if (textStatus === 'success') {
            var data = qXHR.responseText
            appendedContainer.hide();
            appendedContainer.append(data);
            appendedContainer.fadeIn();
        }
      }
    });

});

$(".mylink").on("click", function(event) { alert("new link clicked!");});

The content to be loaded:

<div>some content</div>
<a class="mylink" href="otherurl">Link</a>

This question is related to javascript jquery html ajax jquery-events

The answer is


Use event delegation for dynamically created elements:

$(document).on("click", '.mylink', function(event) { 
    alert("new link clicked!");
});

This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/


For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready" For e.g :

$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
    e.preventDefault();
    var url = $(this).attr('action');
    $.ajax({
        type: 'post',
        url: url,
        data: $(this).serialize(),
        success: function (data) {
            // DO WHAT YOU WANT WITH THE RESPONSE
        }
    });
});

});


if your question is "how to bind events on ajax loaded content" you can do like this :

$("img.lazy").lazyload({
    effect : "fadeIn",
    event: "scrollstop",
    skip_invisible : true
}).removeClass('lazy');

// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
    $("img.lazy").lazyload({
        effect : "fadeIn",
        event: "scrollstop",
        skip_invisible : true
    }).removeClass('lazy');
});

so you don't need to place your configuration to every you ajax code


If your ajax response are containing html form inputs for instance, than this would be great:

$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) { 
if (this.value == 'Yes') {
  // do something here
} else if (this.value == 'No') {
  // do something else here.
} else {
   console.log('The new input field from an ajax response has this value: '+ this.value);
}

});

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

Example -

$( document ).on( events, selector, data, handler );

use jQuery.live() instead . Documentation here

e.g

$("mylink").live("click", function(event) { alert("new link clicked!");});

For ASP.NET try this:

<script type="text/javascript">
    Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.


Important step for Event binding on Ajax loading content...

01. First of all unbind or off the event on selector

$(".SELECTOR").off();

02. Add event listener on document level

$(document).on("EVENT", '.SELECTOR', function(event) { 
    console.log("Selector event occurred");
});

If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!

Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:

$('.parent-element').on('click', '.mylink', function(){
  alert ("new link clicked!");
})

Some more reading on the subject:


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to jquery-events

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function Detect Close windows event by jQuery How to bind Events on Ajax loaded Content? Get clicked element using jQuery on event? jQuery click events firing multiple times jQuery.click() vs onClick Bootstrap onClick button event Difference between $(this) and event.target? Getting the class of the element that fired an event using JQuery Attaching click event to a JQuery object not yet added to the DOM