Chris Chris - 7 months ago 17
Javascript Question

Replace div content from one page with div content from another

I have a page with links in a nav. When a user clicks Page B, I'd like to load content from Page B into the div #main-text of Page A but I can't seem to get it to work. I'm very new to js, so be easy on me.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$("#nav_a").on("click", function(){
$("#main_text").load("pageA.html");
});
$("#nav_b").on("click", function(){
$("#main_text").load("pageB.html");
});
});
</head>
</script>

<body>
<div class="nav">
<ul>
<li><a id="nav_a" href="#">Page A</a></li>
<li><a id="nav_b" href="#">Page B</a></li>
</ul>
</div>
<div id="main_text">Page A</div>
</body>
</html>

Answer

If the pages are from the same domain as the page with the script and contain valid (x)html, then it should work.

Note: Ajax does NOT work from file system. It needs all files to come from a web server.

I would personally do

$(".nav a").on("click", function(e){ 
  e.preventDefault(); // cancel the click
  $("#main_text").load("page"+this.id.split("_")[1].toUpperCase()+".html"); 
});