Home > Enterprise >  How do I change placeholder content in javascript per page
How do I change placeholder content in javascript per page

Time:08-18

How do I change placeholder content with javascript?

I have a website with multiple .html pages, and for easy editing I'm using two placeholders on every page: one with the navigation bar, and one with the main skeleton of the content, like this:

    <body>
      <div id="nav-placeholder">
      </div>
      <div id="content-placeholder">
      </div>
    </body>

The nav bar and content are both in seperate files and are loaded into the pages with an external javascript file like this:

$(function(){
  $("#nav-placeholder").load("nav.html");
});

$(function(){
  $("#content-placeholder").load("content.html");
});

So far, it all works nicely. Now, I'm trying to alter the content separately for each page (with JS), but I'm not sure how to do that or if that's possible? Part of content.html is for example `

<h2 id="subheader1">Title</h2>

I'm trying to change the #subheader1 content in the javascript file like so:

$(function(){
  $("#nav-placeholder").load("nav.html");
});

$(function(){
  $("#content-placeholder").load("content.html");
});

$(document).ready(function() {
  document.getElementById("subheader1").outerHTML = "test" ;
});

but that doesn't work (this is aimed at all pages, but it still doesn't work). Probably because it's only seeing the placeholder DIV in index.html and not it's content?

I tried placing the subheader1 div in the index.html to test, and then it did work, but that would take away the efficiency of the placeholder.

Is there any way to do this (or another way to be more efficient with pages with the same (DIV) layout but different text?)

Thanks!

CodePudding user response:

The load method is not synchronous, so

$(document).ready(function() {
  document.getElementById("subheader1").outerHTML = "test" ;
});

is executed before the html is loaded in the page.

The doc suggest using a callback function.

it is executed after post-processing and HTML insertion has been performed

I had success using this in my js file:

$(document).ready(function() {
    $(function(){
        $("#nav-placeholder").load("./nav.html", function() {
            document.getElementById("insideNav").outerHTML = "It works !" ;
        });
    });
});

with <h2 id="insideNav">Original Nav Bar</h2> in my nav.html.

  • Related