What is the best method for loading multiple HTML files into a Div container?

Recently, I made the decision to improve the look of an online manual I have been working on for my company by incorporating Bootstrap. The manual is structured with a tree-view that contains titles linking to HTML files with information and CSS stylesheets. Initially, I loaded this content into an iframe, but found it problematic when applying CSS. Therefore, I have shifted to using DIVs instead.

The question at hand:

Is there a way to load multiple HTML files into a single DIV by clicking on each title?

All titles are within "a" tags which previously could be targeted in the iframe, but now poses challenges with DIVs.

I have experimented with JavaScript and JQuery, managing to create functions to load specific HTML files. However, attempts to add parameters or use InnerHTML have resulted in issues identifying paths for these files. It is important to note that these files are locally hosted on a server.

Note: The following code snippet illustrates part of what has been attempted...

Javascript:

     <script type="text/javascript">
        $(document).ready(function(){
          $('#content').load('intro.html')
        });
     </script>

HTML:

<div class="bg-light border-right" id="sidebar-wrapper">
      <div class="list-group list-group-flush">
        <ul id="tree3" class="list-group-item list-group-item-action bg-light">          
            <li><a href="PATHFILE_1">TITLE 1</a>
                <ul>
                    <li><a href="PATHFILE_2">TITLE 2</a></li>
                    <li><a href="PATHFILE_3">TITLE 3</a>
                </ul>
            </li>
       </div>
</div>

The objective is to display all the specified files within this div:

<div id="page-content-wrapper">
  <div class="container-fluid">
    <div id="content">
      HERE THE HTML FILES WILL LOAD
    </div>
  </div>
</div>

Answer №1

If you want to selectively load content when clicking on certain links within a div, consider adding a class to those specific a elements, like class='dynamic'. Then, attach a click handler to all a.dynamic elements, extract the link using the href attribute of the target element, and use preventDefault to stop the default action (navigation):

$(body).on("click", "a.dynamic", function(event) {
  $('#content').load(event.target.href);
  event.preventDefault();
}

Don't forget to include the class in your links:

<a class="dynamic" href="PATHFILE_2">TITLE 2</a>

Ensure that the HTML loaded dynamically only contains partial content without the html or body tags. It's also advisable not to use a elements for triggering the load operation:

<div class="dynamic" data-href="PATHFILE_2">TITLE 2</div>

To fetch the URL, you can use this approach:

$('#content').load(event.target.dataset.href);

Answer №2

It is not possible to load multiple HTML files in a single div container, as far as I am aware.

However, you can achieve a similar result by using multiple nested div elements within your main container, like #content. These nested divs can be generated dynamically when a hyperlink is clicked, with each one loading a different HTML file.

The basic HTML structure remains the same as shown above. In JavaScript / jQuery, the implementation might look something like this:

$('#tree3').on('click', 'a', function (e) {
  e.preventDefault(); 
  e.stopImmediatePropagation(); 

  // clear the content div
  $('#content').empty(); 

  let parentLi = $(this).closest("li"); 

  // load the HTML content for the clicked hyperlink
  let dynamicDiv = $('<div></div>'); 
  $('#content').append(dynamicDiv); 
  dynamicDiv.load($(this).attr('href'), function(){
    // done loading the main HTML content 
  });

  // check if there are sub lists inside the li element
  let subList = parentLi.children("ul");
  if(subList.length && subList.length > 0){
    $.each(subList.children("li"), function(k, v){
      let subLi = $(v); 
      let hyperlink = $('a', subLi).attr('href'); 

      // load the HTML content for each sub entry
      let dynamicDiv = $('<div></div>'); 
      $('#content').append(dynamicDiv); 
      dynamicDiv.load(hyperlink, function(){
        // done loading...
      });
    });
  }
}); 

If you need more than two levels in your list, you can modify the code to make it recursive. This way, instead of iterating through the li elements only once, you would also check if those elements contain additional sublists recursively. The core logic for generating and loading the HTML content into divs will remain unchanged.

For styling purposes, I suggest adding overflow-y: auto to the main #content container. This will ensure that there is only one scrollbar for the entire content, while the dynamically generated divs adjust their height based on the HTML content.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Confusion arises from conflicting Vue component script indentation guidelines

As I work on setting ESLint rules for my new Vue project, I am extending both eslint-plugin-vue and airbnb. All is well except for one issue - the indentation of the tag inside Vue components. The usual accepted format looks like this: <script> ex ...

What is the best way to extract values from a JavaScript function?

As someone who is new to Javascript, I am interested in learning how to retrieve values from a function. In the given code snippet, my goal is to extract TheName, TheHeight, TheGender, and TheSexuality when executing the function so that I can utilize the ...

Is there a reason why the JSX select element does not automatically select the option (implementing 'selected')? I'm unsure if I am overlooking something

In my HTML, I have a snippet of code that defines a custom <SelectField> component using a <select> tag like this: export default function SelectField(props) { /* PARAMETERS: - fieldname (String) - fieldID (String) - options (A ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

The Laravel function is not returning as expected on the server

I'm facing an issue with my Laravel project. When the validator fails, the return back function works fine on localhost but on the server it redirects to the root URL. Can anyone help me resolve this problem? Here is my controller code: public functi ...

Using Python with Selenium, attempt to click on a button designated as type="button"

I've been trying to click on a button in this Airbnb listing but none of the codes I tried seem to work. Here is one example of the HTML code: <li data-id="page-2" class="_1eqazlr"> <button type="button" class="_1ip5u88" aria-label="Page 2 ...

"Enhance your website's loading speed with the Google Page Speed Up

Hi, I've been using the Google PageSpeed Module and have created a .htaccess file to optimize my website (www.anetoi.com). I tried using combine_css to merge my CSS files but it didn't work as expected. I followed Google's instructions but s ...

Tab Focus discrepancy observed in Mozilla browser

Tab Focus issue with elements on Mozilla Firefox: <div class="editor-field"> <div> <%: Html.TextBox(model => model.AddressLine1, new { maxLength = 30, style = "width:300px", tabinde ...

The setTimeout functionality is executing faster than expected

In my selenium test, I've noticed that the setTimeout function consistently finishes about 25% faster than it should. For example, when waiting for 20 seconds, the function completes after only 15 seconds. test.describe('basic login test',f ...

Sending parameters to a personalized Angular directive

I am currently facing a challenge in creating an Angular directive as I am unable to pass the necessary parameters for displaying it. The directive code looks like this: (function () { "use strict"; angular.module("customDirectives", []) .directive ...

Assistance with jQuery in Javascript is needed

Currently, I am in search of an effective vertical text scroller. My desired scroller would move vertically in a continuous manner, ensuring there is never any empty space while waiting for the next text to appear. I am open to using either JavaScript or ...

The jQuery UI Sortable functions are being triggered at lightning speed

I am currently working on a project where users can create a seating chart, add rows and tables, and move the tables between different rows. The functionality for adding rows and moving tables already exists in the code. However, I am facing an issue where ...

Display a confirmation modal before triggering $routeChangeStart in AngularJs, similar to the window.onbeforeunload event

When a user chooses to stay on the page as the route starts to change, the original route remains intact but the form directives are reloaded. This results in the loss of all checkbox and input values, resetting them to their defaults. If a user closes th ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...

Creating a Dynamic Navigation Bar with HTML and CSS

I've been exploring the code on w3schools.com, and while there are some great examples, I'm struggling to understand it all. Unfortunately, there aren't any instructions on customizing the code for a third level of menus. Can someone simplif ...

Validating Firebase data for null values

Hey there, I'm currently working on a simple coding project but seems to be encountering some roadblocks. The main objective of the code is to determine if a username exists in the system or not. Here's a snippet of the data structure and codes ...

Seeking guidance on utilizing JavaScript for implementing an onclick event

I am exploring the realm of Event tracking with Google Analytics. To make this happen, I know that I must include an onclick attribute to select links (those specifically requested for tracking) in the following manner: <a href="http://www.example.com" ...

Trigger a modal from one sibling Angular component to another

My application utilizes an Angular6 component architecture with the following components: <app-navbar></app-navbar> <app-dashboard></app-dashboard> The Dashboard component consists of: <app-meseros> </app-meseros> < ...

I'm looking for the location of Angular Materials' CSS directives. Where can I find them?

Currently, I am using components from https://material.angularjs.org/latest/ for a searcher project. One specific component I am working with is the md-datepicker, and I would like to implement some custom styles on it such as changing the background colo ...

What causes the discrepancy in smoothness between the JavaScript animation when offline versus its choppiness when online, particularly on AWS

Recently I delved into game development using HTML5/CSS/JS and embarked on a small project. Check out the game here at this AWS storage link: If you open the game and press SPACE, you'll notice that the ball starts moving with occasional brief pauses ...