I'm creating a simple dashboard and i want to change the section part of the pages. to change this i used innerHTML. but when i run it the UI is not changing and the value in the console is not changing as well.
what i want to do is to change content of the pages with html
files and not touch the sidebar. what i'm getting is it doesn't change it but when i use it int the URL tag it works and when clicked after many click it works sometimes.
the Javascript file. is as follows
const route = (event)=>{
event = event || window.event;
event.preventDefault();
window.history.pushState({}, "", event.target.href);
routeHandler();
};
const routes = {
404: "/html/404.html",
"/": "/html/home.html",
"/school" : "/html/school.html",
"/student" : "/html/student.html"
};
const routeHandler = async ()=>{
const path = window.location.pathname;
const route = routes[path] || routes[404];
const html = await fetch(route).then((response)=> response.text());
console.log(html);
document.getElementById("main-page").innerHTML = html;
};
my index.html
body
<div >
...
<li>
<a href="/" onclick="route()">
<i class='bx bx-grid-alt'></i>
<span >Dashboard</span>
</a>
<ul >
<li><a href="#" >Dashboard</a></li>
</ul>
</li>
...
</div>
...
<section id="main-page"></section>
<script src="/script/router.js"></script>
<script src="/script/index.js"></script>
other pages are as follows
<div >
<h1>Course Section</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed rem non doloribus voluptatibus perferendis alias ea ratione nulla inventore beatae exercitationem totam velit assumenda enim vitae, fugiat molestias rerum nemo?</p>
</div>
so why is this not working?
CodePudding user response:
Maybe you should try using XML HttpRequests. Basic example to understand how it works:
<!DOCTYPE html><html>
<body>
<div id="sidebar">
<button type="button" onclick="loadXMLDoc('A.txt')">Change Content A</button>
<button type="button" onclick="loadXMLDoc('B.txt')">Change Content B</button>
</div>
<div id="main-page">
</div>
<script>
function loadXMLDoc(chosen_option) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("main-page").innerHTML =
this.responseText;
}
};
xhttp.open("GET", chosen_option, true);
xhttp.send();
}
</script>
</body>
</html>
This way all "dashboard" stay same, but browser gets only content for "main-page" div.
You need to have content files (in this example A.txt and B.txt). In content files you should put content for main div.
CodePudding user response:
Consider setting iframe src with your javascript and style it appropriately.