How to bind jQuery events within dynamic content returned via Ajax?

jQueryWeb DevelopmentFront End Technology

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>
raja
Published on 20-Dec-2017 14:29:43
Advertisements