What I want to achieve:
- Add an event listener to all
hrefs
in thelist
withclass="listen"
. - When user clicks on any list item then replace the content of the
div
withid="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
Your loadDoc function doesn’t do anything.
You need to use fetch using x as the url.
Based on this similar answer on how to fetch partial HTML content from files
onclick
event.preventDefault()
to prevent the default browser behavior (follow anchors)Having pages like:
page1.html
in the root of your projectpageN.html
This would be your main page: