2

I'm using a template.html file to house my header & menu bar and using JS to insert page content per individual index.html files. I house template.html in my root file and subfolders house an index.html (which pulls in the template.html as an object) and script.js.

I need the index.html file to load the script.js file while still having the script.js file apply to the template.html file, but cannot figure out how to have the JS reference inside the index.html object. I've seen something done like this before-ish for iframes, but could not get it to apply the same way for object elements.


Here's the shortened files:

template.html

<!-- header & menu html -->
<div>
  <div id="middleLeft"></div>
  <div id="middleRight"></div>
</div>

references/index.html

<object type="text/html" data="../template.html"></object>

references/script.js

jQuery(function ($) {

window.onload = function() {
  $('#middleRight').innerHTML = rightText;
  $('#middleLeft').innerHTML = leftText;
}

var leftText = "<p>left text</p>";
var rightText = "<p>right text</p>";

As is, the script.js only works if it's loaded within the template.html, but it needs to be loaded within the index.html. Is there a way to load it in index.html but still let it reference elements within the template.html object? Thanks for your help!

1 Answers1

0
  • jQuery $() has no .innerHTML method, rather .html()
  • Assign an ID to your <object> so you can easily target it
  • You should wait for the <object> is loaded
  • You can access than the content using contentDocument

Here's an example

<object id="myObj" type="text/html" data="../template.html"></object>

jQuery(function ($) {

    var leftText = "<p>left text</p>";
    var rightText = "<p>right text</p>";

    $("#myObj").on("load", function() {

        console.dir(this.contentDocument);                 // #document
        console.dir(this.contentDocument.documentElement); // html

        var $doc = $( this.contentDocument );

        $doc.find('#middleRight').html( rightText );
        $doc.find('#middleLeft').html( leftText );

    });

});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Thanks, Roko! I had to switch 'load' to 'ready', else the function would never run, is that okay? I always get undefined for the first console.dir. Code looks like this now $("#holder").ready(function() { console.dir(this.contentDocument); // #document console.dir(this.contentDocument.documentElement); // html var $doc = $( this.contentDocument ); $doc.find('#middleRight').html( rightText ); $doc.find('#middleLeft').html( leftText ); }); – Steffanie Nestor May 06 '17 at 05:00
  • @SteffanieNestor The above example works on my localhost (local server) - so it should work for you too - just make sure your path to `template.html` is well set . – Roko C. Buljan May 06 '17 at 05:31