MTavares
MTavares

Reputation: 27

Load html snippet using jquery

I'm fairly new to JavaScript and I'm trying to understand how I can load html snippets into a html page, but using an element trigger inside another snippet already loaded.

For example, the below works fine: the button with id 'about-button' (present in my homepage) is loading the right html content into the page:

$(document).ready(function(){
  $("#main-content").load("snippets/index-snippet.html");

  $("#about-button").click(function(){
    $("#main-content").load("snippets/about-snippet.html", function(responseTxt, statusTxt, jqXHR){
        if(statusTxt == "error"){
            alert("Error: " + jqXHR.status + " " + jqXHR.statusText);
        }
    });
  });
});

However, if I then try to do the same thing with an element id that was loaded and is inside of index-snippet.html then that doesn't work:

$(document).ready(function(){
        $("#about-button-inside-html-snippet").click(function(){
        $("#main-content").load("snippets/about-snippet.html", function(responseTxt, statusTxt, jqXHR){
            if(statusTxt == "error"){
                alert("Error: " + jqXHR.status + " " + jqXHR.statusText);
            }
        });
    });
});

Is there a function similar to $(document).ready but for other functions? Maybe a way to run this function on click after $("#main-content").load("snippets/index-snippet.html"); ran?

Let me know if you need more explanation. Due to my limited knowledge in the area I'm struggling to find the right words.

Thanks!

Upvotes: 0

Views: 786

Answers (1)

MTavares
MTavares

Reputation: 27

As per gaetanoM 's reply (many thanks!), this was solved by using the following:

$(document).on('click', "#about-button-inside-html-snippet", function(){
    $("#main-content").load("snippets/about-snippet.html", function(responseTxt, statusTxt, jqXHR){
        if(statusTxt == "error"){
            alert("Error: " + jqXHR.status + " " + jqXHR.statusText);
        }
    });
});

Upvotes: 1

Related Questions