0

I have an html page which gets loaded via ajax, the newly loaded html content has the following html. It typically works great when I load the html first and then initialize the javascript.

<a href="" class="ajax-button" data-url="/account/change-password">Change password</a>

My js:

$('.ajax-button').on('click', OnLoadContent);

function OnLoadContent(e) {
    e.preventDefault();
    var pageurl = $(this).data('url');
    $.ajax({
        type: "GET",
        url: pageurl,
        success: function(data) {
            alert(data);
            $("#content-container").html(data);
            window.history.pushState({path:pageurl}, '', pageurl);
        },
        error: function(response) {
           alert("ERROR:" + response.responseText);
        }
    });
}

However since it's new html content that's being loaded I think the problem is the javascript already exists when the html content is loaded via ajax, so the click functionality doesn't work unless I click again. I'm wondering how I can fix this?

Howard
  • 3,648
  • 13
  • 58
  • 86

1 Answers1

2

Delegate the click higher up the dom...

$('body').on('click', '.ajax-button', OnLoadContent);

brbcoding
  • 13,378
  • 2
  • 37
  • 51