I am trying to figure out why jQuery is not binding to all future 'click' events on my page. It only works the first time I do this. The AJAX request fires, and displays adds the correct data to the DOM, however any subsequent attempts do not fire. When I select a button 'View All Dealerships', the AJAX requests returns JSON array of the dealerships and displays them on the page.
$(function(){
$("body").on("click", "#all-dealerships", function(e){
let path = $(this).attr("href");
$.ajax({
url: path,
dataType: 'json',
success: function(response){
var source = $("#dealerships-template").html()
var template = Handlebars.compile(source)
var result = template(response)
var a = () => document.getElementsByTagName("body")[0].innerHTML = ""
a()
document.getElementsByTagName("body")[0].innerHTML += result
}
})
e.preventDefault()
})
})
The variable names and structure is just for testing. Body is a static element that does not change. I tried wrapping the button in a div and using that as the parent object that binds the event, however I get the same result. The page loads just not with AJAX. The event only gets bound when I do a full page refresh. Navigating to other pages on the site does not fix the problem.
The button that triggers the AJAX request is not present when the new elements are added to the DOM. It gets removed. The action of navigating back to that button does not re-trigger the click event.