I have made a successful test page that satisfies my goals of using javascript ( jQuery specifically ) to add and remove content from a webpage.
<!doctype html> <head> <title>test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="main"></div> <script> const foo = `<h1 id="title">Page-Foo-One</h1></div> <p>Some text about foo foo foo.</p> <h3 id="bar_link">Link to bar</h3>`; const bar = `<h1 id="title">Page-Bar-Two</h1></div> <p>Some text about bar bar bar.</p> <h3 id="foo_link">Link to foo</h3>`; $ ("#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); }) </script> </body> </html>
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 ( dozens of links per page , each one putting in different content ) the “.on(click)” chain would get very hectic.
How else could I handle this situation?
I know that I could just make two different .html files ( foo and bar ) and setup simple ‘a href=’ links 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.
Thanks for your time!