-1

I create HTML files of press articles as separate entities as they can appear in several places in the website. In one place I want the ability to display all articles for a particular year into a specific div Called "news".

I found the w3 schools include html code this is fine except it always displays the included HTML as a new window. I have tried several methods but no luck. Do you know what coding changes i would need to do in order to achieve my aim. I think I need a (Document.getelement by id) but cannot work out where to put the code.

enter code here

<!DOCTYPE html>
<html>
<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
   elmnt = z[i];
   /*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
  /*make an HTTP request using the attribute value as the file name:*/
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4) {
      if (this.status == 200) {elmnt.innerHTML = this.responseText;}
      if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
      /*remove the attribute, and call this function once more:*/
      elmnt.removeAttribute("w3-include-html");
      includeHTML();
    }
  }      
  xhttp.open("GET", file, true);
  xhttp.send();
  /*exit the function:*/
  return;
 }
  }
};
</script>

<body>

<div w3-include-html="content.html"></div> 

<script>
  includeHTML();
</script>

</body>
<html>
<!-- Content.html -->
<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">Animated Buttons</a><br>
<a href="howto_css_modals.asp">Modal Boxes</a><br>
<a href="howto_js_animate.asp">Animations</a><br>
<a href="howto_js_progressbar.asp">Progress Bars</a><br>
<a href="howto_css_dropdown.asp">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.asp">Click Dropdowns</a><br>
<a href="howto_css_table_responsive.asp">Responsive Tables</a><br>
</html>
j08691
  • 204,283
  • 31
  • 260
  • 272
  • Any particular reason you want to do that with Javascript, instead of using your back-end language, or SSI if you want to keep it HTML only? It seems that you will need to get an index of those files anyway, and you might as well pool the content together for output. Suppose you have 100 articles, and you want to display them all. Doing that with JS will generate 100 HTTP requests and conceivably torture the user's browser in the process. Compiling it into HTML behind the scenes will be done in 1 request. – Markus AO Jul 16 '20 at 17:54
  • But if you must, here's a spectrum of leads: https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript – Markus AO Jul 16 '20 at 17:54
  • I will start reading though the leads. The reason I was going down this route is the website is for a local Lions International charity and we would like to present some of the HTML content is two places. – Grahama Roberts Jul 16 '20 at 18:51
  • How are you pooling together your indexes? 1. Are they HTML files in folders sorted by year, or something like that? 2. Will you manually add in the names for all the HTML pieces you intend to include on a given page? – Markus AO Jul 16 '20 at 19:25
  • Apologies i loaded up the wrong Content.html. This html has all the HTML referring to 2019 there are other HTML for other years. The Aim is to display by year all our press, and also have the ability to reference one of the items in another section of the website i.e projects. I will manually add in the Html pieces. – Grahama Roberts Jul 17 '20 at 08:38
  • Apologies i loaded up the wrong Content.html. The above html has all the HTML referring to 2019 there are other HTML for other years. The Aim is to display by year all our press, and also have the ability to reference one of the items in another section of the website i.e projects. I will manually add in the Html pieces. – Grahama Roberts Jul 17 '20 at 08:46
  • How many articles do you already have? If you have 100+, it might be an idea to write a script to index all the files, or use other tools to extract all the filenames per year, rather than copy-pasting everything manually. – Markus AO Jul 17 '20 at 19:11

1 Answers1

1

I would advise against the JavaScript approach; and simply opt to render your cumulative pages at the server end, and then serve out the built-up HTML. Here's the elementary how-to.

The simplest thing to do would be to have a plain text file with all the articles for a given month listed. Suppose we put the following into indexes/Press2019.txt, one entry per line:

Apr20.html
Mar20.html
oct19.html
sept19.html
July19.html
...

Then, suppose we have a simple PHP file, press.php, as follows (please read the inline comments to understand what the code is doing):

<!DOCTYPE html>
<html lang="en">

<?php
// Validate the "year" request as a valid integer
$year = isset($_GET['year']) ? filter_var($_GET['year'], FILTER_VALIDATE_INT) : false;
empty($year) && die('Invalid Year!');

// Check if an index for the year exists
$path_index = "indexes/Press{$year}.txt";
!is_file($path_index) && die("No press index for year {$year}!");

// Load list of articles
$texts = file($path_index, FILE_IGNORE_NEW_LINES);

// Function for HTML title & header
function make_header($title) {
    echo "<head><title>{$title}</title></head>";
    echo "<body><h1>{$title}</h1>";
}

// Output header
make_header("All Press Articles for Year {$year}");

// Output all articles
foreach($texts as $file) {
    $path = '/html/press/' . $file;
    $html = file_get_contents($path);
    $html = parse_body($html); // read below for explanation
    echo $html;
?>
</body>
</html>

This would load and output all the articles in your list into one page.

I'm assuming that your individual articles are also static HTML files with <html>, <body> etc. tags included. If not, you can remove the parse_body function above. If yes, we need to clean them up. (This would also be an issue with the JavaScript approach you experimented with in the OP.)

We can accomplish this with a simple regular expression function included in the press.php file:

function parse_body($html) {
    if (preg_match('#<body>(.+)</body>#is', $html, $match)) {
        return trim($match[1]);
    }
    return 'No content matched!';
}

Then, all you'd need to do is make a link like press.php?year=2019, and have plain text page index files in the indexes folder. You could double up your index files to generate the HTML you posted in your comment to the OP, suppose a file called monthly.php, with the second half of the code above replaced with:

// Output header
make_header("Links to Monthly Press Articles for Year {$year}");

// Output links to monthly pages
foreach($texts as $file) {
    echo "<a href="/html/press/{$file}">{$file}</a>";
}

That would give you monthly summaries with links: Simply link to monthly.php?year=2019 (or whichever year) to get a year's links summary. Less manual HTML coding = less errors, easier updating, and more time saved for actual productive work. :)

Now, there are fancier ways of doing this. This would be the first step in leveling up from manual HTML writing. With a bit of experimentation and a couple of basic PHP tutorials, you could easily customize this and adapt it to different contexts.

This isn't an answer to tweaking the JavaScript in the OP to do the job; but it is a fairly simple solution to the actual question, "I am trying to include many HTML files into a specific DIV". This answer turned out to be "code writing service", which SO by definition is not. But you're on with a good cause, so. Best of luck, hope this helps.

Markus AO
  • 4,771
  • 2
  • 18
  • 29
  • Thank you Marcus. I will definitely try the PHP approach . I will need to do some PHP tutorials to fully understand how the above works. – Grahama Roberts Jul 17 '20 at 18:53
  • You're welcome. I've intentionally kept it very basic. Need to understand: 1. basic syntax of the language, 2. loop (here `foreach`), 3. conditional check (`if/else`), 4. custom function, 5. basic built-in functions. These won't get you into the stratosphere, but they will help you eliminate a lot of manual work. – Markus AO Jul 17 '20 at 18:58
  • On a note of clarification; `if(true) { } else { }` is the basic condition check. In the code above, I've used two "shortcuts" that you can see on the line starting with `$year`. One is called "ternary operator assignment": `$var = (condition) ? 'yes' : 'no';`. You could also say `if (condition) { $var = 'yes'; } else { $var = 'no'; }`. It's just a shorter way of writing it. The second one, `&&`, is a simple logic chain. `(condition) && echo 'yes!'`, where the right-side statement is only executed if the left-side statement is `true`. One could also say, `if (condition) { echo 'yes!'; }`. – Markus AO Jul 17 '20 at 19:07
  • Actually found your website and the press section. Your press HTML files actually *don't have a `` tag* around the content, it's simply inside `...` tags. In that case, you'd want to modify this:`if (preg_match('#(.+)#is'...`. You could also just get rid of the function, and have `$html = str_replace(['', ''], '', $html)` in the main loop to clean up the tags that shouldn't be nested. (Assuming a consistent structure in the html docs.) – Markus AO Jul 17 '20 at 19:25
  • Have checked all HTMl file then begin and end with ..... So I will amend the code as you suggested. I am currently testing the code on my pc using Wampserver64. I keep getting the no press index message. I have tried changing the path to a different directory but still same message, any ideas. – Grahama Roberts Jul 19 '20 at 12:31
  • Using below to call the press.php.
    – Grahama Roberts Jul 19 '20 at 12:35
  • After a bit of file moving around have fixed all issues. had to make the fix a function. as ever time i added it into main loop i kept getting unexpected end of file syntax messages. Only think left is to make contents only appear in "content" div as opposed to a new page. will look and see how to do this . again thanks for your help – Grahama Roberts Jul 19 '20 at 16:17
  • Glad to hear you're making headway with the project. If you run into other specific problems, feel free to start a new question with a summary of the issue you're facing. Best of luck and happy studies! – Markus AO Jul 19 '20 at 18:46