0

I am new to JavaScripts, and I'm attempting to build a single page navigation blog using bootstrap. I have a basic index.html which has the following code:

<Some bootstrap navbar on top that includes "home", "about", "contact">

<div id="content">
</div>

<script src="navigation.js"></script>

The navigation.js file has a window.addEventListener("hashchange", navigate) that just listens for the hashchange and sets the innerHTML of the content-div based on the hash. The actual content for each of the pages is seperated into partial html files, for example about.html that only has <p>About</p> for now, and these partial htmls are fetched using AJAX.

So far everything works, but for the home.html I don't have only static HTML, i also want to execute a JavaScript that renders all the blog posts. Basically I would want home.html to include:

<div id="posts">
</div>
<script src="renderposts.js"></script>

Where renderposts.js is a script that sets the innerHTML of the posts-div to include all my blog posts.

This doesn't work though, renderposts.js is not executed. Am I thinking about this the wrong way and how should I approach this? The only work-around that I've managed is to include the code in the navigation.js file instead, and execute it with an if-statement checking if the location.hash is currently "#home". This is obviously a very ugly solution.

2 Answers2

0

I didn't find this post when searching the topic but it appeared in the related section after posting: Load partial html with javascript inside

Basically, changing from contentDiv.innerHTML = content; to jQuerys $('div#content').html(content); fixed the issue. I'm still curious whether this is the "correct" way to go about the principal issue, or if I'm approaching the whole thing incorrectly.

0

One way to handle it is to link renderposts.js from your main page, then in the function that loads home.html, it can then execute the javascript functions. Something like

<script src="navigation.js"></script>
<script src="renderposts.js"></script>
<button onclick="loadHome">Click Me</button>

<script>
    function loadHome() {
        // Some AJAX Requst Here //

        var contentDiv = document.getElementById("content");
        contentDiv.innerHTML = content;
        getPosts();
        renderPosts();
    }
</script>
Aaron Dougherty
  • 727
  • 6
  • 9
  • Excellent, I will play around with this. Thanks! (unfortunately my reputation score is too low to upvote, but your help is much appreciated!) – Jonas Svalin Oct 01 '15 at 09:03