Jeffrey Goines
Jeffrey Goines

Reputation: 955

Load External HTML and Add Event Handler for Element Declared in the HTML

I have a external HTML to be loaded after the main HTML is loaded.

<!--external.html-->
<form id="externalForm">
    <div id="button">Button</div>
</form>

How to add event handler for "button"?

Tried the following code in the main HTML,

<!--main.html-->
<body>
<div id="extForm"></div><!--to be loaded when document.ready-->

<script>
$(document).ready(function() {
    // Fill extForm with div's declared in external.html
    $("#extForm").load("external.html");
}
// button.ready will be triggered after loading external.html
$("#button").ready(handlerCreator());

var handlerCreator = function () {
   return function() {
       alert("Working"); // since button is ready
       $("#button").on("click", function() {
           alert("Not working"); // why?
       });
   };
}

</script>

Upvotes: 1

Views: 1114

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

Button does not have a ready handler... you need to use event delegation

Use event delegation to register the handler for #button

$(document).ready(function () {
    $("#extForm").load("external.html");
})
$("#extForm").on('click', '#button', function () {
    alert('button clicked')
});

or register the handler after the external file is loaded to the dom

$(document).ready(function () {
    $("#extForm").load("external.html", function () {
        $("#button").click(function () {
            alert('button clicked')
        });
    });
})

Upvotes: 3

Related Questions