Search code examples
javascriptjqueryhtmllocalpageload

How can I change the body content onclick some button


I'm using JQuery To load the navbar and body of my website and I want to change the body content onclick some button in the navbar Can I use JavaScript to do that ? how can I ?

Please I been looking for a solution but I didn't found anythings . Thanks in advance

html

 <header>
      <script>
        $(function () {
          $("header").load("./dist/includes/navbar.html");
        });
      </script>
    </header>
    <!-- END of Section NavBar  -->
    <main>
      <script>
        $(function () {
          $("main").load("./dist/includes/home.html");
        });
      </script>
    </main>
    <!-- Section Footer  -->
    <footer class="footer">
      <script>
        $(function () {
          $("footer").load("./dist/includes/footer.html");
        });
      </script>
    </footer>

I want to chage the home.html loaded file when i click a button with id="nav-link"

Here is a screenshot

Screen Shot


Solution

  • Consider the following code.

    $(function() {
      // Load content
      $("header").load("./dist/includes/navbar.html");
      $("main").load("./dist/includes/home.html");
      $("footer").load("./dist/includes/footer.html");
    
      // Prpgram Events
      $("header").on("click", "button", function(ev) {
        console.log("Nav Button was clicked");
        $("main p").append("<a href='#'>New Page</a>");
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!-- Section NavBar  -->
    <header></header>
    <!-- END of Section NavBar  -->
    <main></main>
    <!-- Section Footer  -->
    <footer class="footer"></footer>
    <!-- END of Section Footer  -->

    Using jQuery we load the content. As the content did not exist in the DOM on ready, we will use .on() to delegate event callbacks on items that have now been loaded.

    So if the following HTML was added to the header, for example:

    <button>Show Link</button>
    

    When this is clicked, it will execute the anonymous callback and append the link into main.

    See More: https://api.jquery.com/on/

    It would be better to use Server-Side Scripting to construct the HTML. Many of them have an Include feature or function that can add the pages into the Output before sending it to the browser so that the Client can work with all the content upfront.