jQuery "on('click')" to toggle webpage content I have made a successful test page that satisfies my goals of using JavaScript ( jQuery specifically ) to add and remove content from a webpage. 



&lt;!doctype html&gt;
&lt;head&gt;
&lt;title&gt;test&lt;/title&gt;
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id="main"&gt;&lt;/div&gt;
&lt;script&gt;

    const foo = `&lt;h1 id="title"&gt;Page-Foo-One&lt;/h1&gt;&lt;/div&gt;
    &lt;p&gt;Some text about foo foo foo.&lt;/p&gt;
    &lt;h3 id="bar_link"&gt;Link to bar&lt;/h3&gt;`;

    const bar = `&lt;h1 id="title"&gt;Page-Bar-Two&lt;/h1&gt;&lt;/div&gt;
    &lt;p&gt;Some text about bar bar bar.&lt;/p&gt;
    &lt;h3 id="foo_link"&gt;Link to foo&lt;/h3&gt;`;

    $("#main").append(foo);

    $("#main").on('click','h3#bar_link', function (){
        console.log("Clicked bar_link");
        $("#main").html("");
        $("#main").append(bar);
    }).on('click','h3#foo_link', function (){
        console.log("Clicked foo_link");
        $("#main").html("");
        $("#main").append(foo);
    }).on('click','h1#title', function (){
        console.log("Clicked title");
        $("#main").html("");
        $("#main").append(foo);
    })
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;




For this simple example where only two possible outcomes exist the code isn't too bad to look at, however I know that if this were inflated to what a full website can entail (e.g. dozens of links per page, each one putting in different content) the .on(click) chain would get very complicated. 

How else could I handle this situation? 

I know that I could just make two different .html files ( foo and bar ) and setup simple anchor links (i.e. &lt;a href="..."&gt;) between them and obtain the same effect but my goal is to have an external source generate the content that is displayed.

I am getting used to JavaScript programming in general so please do point out other ways I can improve what I am doing.
The code pattern:

$("#main").html("");
$("#main").append(bar);


can be simplified to:

$("#main").html(bar);


In general, the code is, clear, easy to read, and well organized. All the decisions among alternatives are reasonable and straight forward. Doing the simplest thing that might work is a good approach because it avoids adding unneeded complexity to the necessary complexity.

The use of template literals rather than strings might be unnecessary complexity because the templating features are not used. Support for template literals is not universal among browsers. The page may break for no reason for some people. To put it another way, using template literals rather than strings creates potential broken pages for no gain in browsers that support template literals.