user2717118 user2717118 - 1 month ago 14
HTML Question

Adding content to a HTML page with Javascript

Okay. So, I am trying to create a page which displays a bunch of notes I have stored on my computer. As I am only going to keep the page on the local-machine, I have thought of keeping these notes as JavaScript functions, in separate documents, which add the note to the page.

However, this has not worked as of yet, and I am struggling to create the effect I would like.

The problem lies, in my opinion, of adding the notes to the page before other script modifies them. At the moment, I am yet to be able to display a single note on the page, and I am receiving no errors.

It would be greatly appreciated if somebody could point out where I went wrong. I would like to be able to add as many notes as I like by simply adding another JavaScript document.

The HTML Document:

<head>
<meta charset="utf-8" lang="en">
<script src="text1.js"></script>
<script>
var colours = [
"rgba(254, 224,198,0.6)",
"rgba(254,240,201,0.6)",
"rgba(180,238,180,0.6)",
"rgba(141,238,238,0.6)",
"rgba(85,152,198,0.6)"
];

var x;

function sectionSelect(){
x = document.getElementsByTagName("section");
}

function colourBG(){
for(var i=0; i<= (x.length - 1); i++){
var z = Math.floor(Math.random() * colours.length);
x[i].style.backgroundColor = colours[z];
};
}
</script>
</head>
<body>

<script>
sectionSelect();
colourBG();
</script>
</body>


Inside of the text1.js document: (this is where I think the problem lies, yet I'm unsure)

(function(){
var content = `
<section>
<h1>Links</h1>
<p><a href="" target="_blank"></a></p> //There are just a bunch of links here
</section>
`;
document.body.insertAdjacentHTML('afterbegin', content); })


Any help would be greatly appreciated. Thanks

Answer

The problem with your text1.js file, is that it's trying to do an IIFE (immediately invoked function expression), but it's not actually invoking it. So you would have to add a () to the end of that script, like so:

(function(){
var content = `
<section>
    <h1>Links</h1>
    <p><a href="" target="_blank"></a></p> //There are just a bunch of links here
</section>
`;
document.body.insertAdjacentHTML('afterbegin', content); })()

Alternatively, you should be able to get rid of the IIFE altogether and just have the file consist of this:

var content = `
<section>
    <h1>Links</h1>
    <p><a href="" target="_blank"></a></p> //There are just a bunch of links here
</section>
`;
document.body.insertAdjacentHTML('afterbegin', content);