Bind jQuery Events within Dynamic Content Returned via Ajax



To bind jQuery events within dynamic content, use event delegation. You can try to run the following code to learn how to bind jQuery events within dynamic content returned via Ajax:

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".loadingAjax").on("click", function() {
    event.preventDefault();
    var url = $(this).attr("href"),
        appendedContainer = $(".append");

    $.ajax({
    url: url,
    type : 'get',
    complete : function( qXHR, textStatus ) {

        if (textStatus === 'success') {
            var data = qXHR.responseText
            appendedContainer.hide();
            appendedContainer.append("<a href='#' class='link'>Hi</a>");
            appendedContainer.fadeIn();
        }
      }
    });
});

$(document).on("click", '.link', function(event) {
    alert("Link clicked!");
});
});
</script>
<style type="text/css">
        a.test { font-weight: bold; }
        body { font-family: sans-serif;}
    </style>
</head>
<body>
<a class="loadingAjax" href="https://www.qries.com"> Click to load Ajax</a>
<div class="append"></div>
</body>
</html>
Updated on: 2020-06-15T07:49:44+05:30

747 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements