Search code examples
javascripthtmlnode.jstwitter-bootstrap-4express-handlebars

Program does not recognize .modal("show") function after appending HTML to page


I am writing a program where a click event handler fires an ajax request to my node server, which then renders info inside of a handlebars partial and sends it back to the client (res.render("partials/scraped-article", data);). The client-side javascript appends this html to the document and shows a modal using the bootstrap .modal("show") function. The program shows the modal the first time the click event handler gets fired, but does not recognize the .modal("show") function afterwards. Is there a way to fix this?

Client-Side Javascript:

$(document).on("click", "#scrape-options li", function(){
    var choice = $(this).text();
    var request;

    if(choice === "website1")
        request = "/scrape/website1";
    else
        request = "/scrape/website2";

    $.ajax({
        type: "GET", 
        url: request
    }).then(function(response){
        $(".news-article").remove();

        $("footer").append(response);

        $('.news-article-img').each(function(i, element){
            $(this).css({'height': ($(this).next().height() + 'px')});
        });

        $("footer h1").addClass("display-none");
        $("#articles-added").text($(".news-article").length);
        $(".modal").modal("show");
    });
});

Solution

  • It turns out that even if you are rendering a partial, the response sent from the server will be embedded in the default template (i.e. it will be a full HTML document). If you simply add this to the DOM, you will be inserting the script for Bootstrap a second time, which will do weird things like disable the $(...).modal function. Instead, you should use the array.split method to extract the body HTML and then append this to the DOM.