skip to Main Content

What I want to achieve:

  • Add an event listener to all hrefs in the list with class="listen".
  • When user clicks on any list item then replace the content of the div with id="SelectedText" with the content of the chosen file.
<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8">
  <title>Read file into div</title>
  <article>
    <h1>My HTMl</h1>
    <ul class = "listen">
      <li><a href="file1.html">Select file 1</a>
      <li><a href="file2.htm">Select file 2</a>
      <li><a href="file2.txt">Select file 3</a>
    </ul>
    <h1>Please find selected content below:</h1>
    <div id = "SelectedText">
      <p>Replace me
    </div>
    <script> magic here </script>
  </article>
<!-- Local file -->
<p>file i contains for example:
<h1>Ipsum dolor sit amet</h1>

I tried:

<!DOCTYPE html>
<html lang="nl">
<meta charset="utf-8">
<title>Test</title>
  <nav>
    <ul>
      <li><a href="#" onclick="loadDoc('/nieuws.htm'); return false;">Nieuws</a>
      <li><a href="#" onclick="loadDoc('/teams/teams.htm'); return false;">Teams</a>
      <li><a href="#" onclick="loadDoc('/links/links.htm'); return false;">Links</a>
    </ul>
  </nav>
  <main id="content">
  <p>Replace me
  </main>

with JavaScript function:

    <script>
    // Load external HTML document in div.
    function loadDoc(x) {
      .then((result) => {
        if (result.status != 200) { throw new Error("Bad Server Response"); }
        return result.text();
      })
      .then((content) => {
        document.getElementById("content").innerHTML = content;
      })
      .catch((error) => { console.log(error); });
    }
    </script>

But I find a solution with event-handlers more elegant.

2

Answers


  1. Your loadDoc function doesn’t do anything.
    You need to use fetch using x as the url.

    fetch(x).then(
    
    Login or Signup to reply.
  2. Based on this similar answer on how to fetch partial HTML content from files

    • Use fetch API
    • use addEventListener instead of inline JS like onclick
    • use event.preventDefault() to prevent the default browser behavior (follow anchors)

    Having pages like: page1.html in the root of your project

    pageN.html

    <h1>This is page N</h1>
    

    This would be your main page:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Read file into div</title>
    </head>
    
    <body>
        <h1>My HTMl</h1>
        <ul class="listen">
            <li><a href="file1.html">Load file 1</a>
            <li><a href="file2.html">Load file 2</a>
            <li><a href="file3.html">Load file 3</a>
        </ul>
        <h1>Please find selected content below:</h1>
        <div id="SelectedText">
            <p>Replace me</p>
        </div>
        <script>
            const loadPartial = async (elAnchor, elTarget) => {
                try {
                    const file = elAnchor.getAttribute("href");
                    const res = await fetch(file);
                    const html = await res.text();
                    const domp = new DOMParser();
                    const doc = domp.parseFromString(html, "text/html");
                    elTarget.innerHTML = ""; // clear old content
                    elTarget.append(doc.documentElement);
                } catch (err) { console.error(err) };
            };
    
    
            const elTarget = document.querySelector("#SelectedText");
            const elListen = document.querySelector(".listen");
    
            elListen.addEventListener("click", (evt) => {
                const elAnchor = evt.target.closest("a");
                if (!elAnchor) return;
                evt.preventDefault(); // Prevent browser following the anchor
                loadPartial(elAnchor, elTarget);
            });
        </script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search