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

Using Vaadin: update Label text with TextField input after Button is clicked

I'm working on a simple Vaadin form where I want the text entered in a TextField to appear in a Label after the user clicks on a Button. Here's the code snippet: package com.example; import javax.servlet.annotation.WebServlet; import com.vaad ...

The Electron BrowserWindow turns dark post execution of the .show() method

Revision: After some tinkering, I discovered that the issue was related to the order in which I created the windows. Previously, my code looked like this: app.whenReady().then(() => { createWindow(); spawnLoadingBlockWindow(); spawnGenerati ...

Should we integrate a MongoDB database calculation app with a POST Controller in sails.js?

The primary function of the application interface is to provide variables that have been initially posted by the client, as well as any subsequent database calculations carried out in real time by a specialized engine. Is it possible to integrate this eng ...

Preventing duplicate submissions in Ajax by serializing form data

I'm having trouble preventing double submissions on my form when I rapidly press the button that triggers a click event. I attempted to disable the button after a successful submission, but it still submits twice. Here is my code: <script> $(do ...

Automatically switch Twitter Bootstrap tabs without any manual effort

Is there a way to set up the Twitter Bootstrap tabs to cycle through on their own, similar to a carousel? I want each tab to automatically switch to the next one every 10 seconds. Check out this example for reference: If you click on the news stories, yo ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

Trigger/cease cron job with the click of a button within a Node.js Express application

I have been working on a project that involves starting and stopping a cron scheduler when a user interacts with a button on the front end. Essentially, clicking the start button initiates the cron job, while clicking the stop button halts the timer. It&ap ...

When trying to load a php page2 into page1 via ajax, the Javascript code fails to execute

Currently, I am in the process of learning PHP and JavaScript. I have encountered a particular issue with a webpage setup. Let's say I have a page called page1 which consists of two input fields and a button labeled 'Go'. Upon clicking the & ...

Incorporating Stripe: Enhancing Online Payments through Redirected Checkout

I am currently in the process of upgrading our checkout system to be SCA compliant. According to the documentation, I must utilize PaymentIntents for this purpose. I have followed the steps outlined in their document found at: https://stripe.com/docs/payme ...

Can you identify the nature of the argument(s) used in a styled-component?

Utilizing typescript and react in this scenario. Fetching my variable const style = 'display: inline-block;' Constructing a simple component export const GitHubIcon = () => <i className="fa-brands fa-github"></i> Enh ...

The secrets behind the seamless, fluid layout of this website

Upon exploring the website www.emblematiq.com, I noticed that it features a fluid/liquid layout. Despite analyzing the code, I am unable to decipher how this effect is achieved. The layout appears to be fixed width with the canvas element set at 1180px. D ...

Is there a comparable solution like Fabric in Javascript or Node.js?

One thing that I really appreciate about Fabric is how it simplifies the deployment process to multiple servers, especially with its strong support for SSH. But since our project is based on node.js, it would be ideal if we could achieve a similar function ...

Tips on how to trigger the function upon receiving the response value by concurrently running two asynchronous functions

export default { data: () =>({ data1: [], data2: [], lastData: [] }), mounted() { asynchronous1(val, (data)=>{ return this.data1 = data }) asynchronous2(val, (data)=>{ return this.data2 = data }) f ...

Employing the findOne method repeatedly in a loop can significantly slow down operations in Node.js

Currently, I am working on a project using Node.js in conjunction with MongoDB, specifically utilizing Monk for database access. The code snippet I have is as follows: console.time("start"); collection.findOne({name: "jason"}, function(err, document) { ...

Transferring Data from Python Script to Browser (with an xserver running on a Linux system)

Looking for suggestions on how to efficiently transfer data from a Python script to a web browser. The Python script, as well as the browser, are operating under an xServer environment in Linux (specifically Raspbian on Raspberry Pi). The script is respon ...

I successfully coded a function without utilizing the function key, but unfortunately I am encountering difficulties when trying to output the

I have created a function without using the function keyword. The function should take the age above 15 and push it into an array. I have been able to do that, but I am struggling to print the result. Can anyone help me with this? my code <script> ...

avoiding the duplication of effects on an object when new objects are added via ajax

Currently, I am facing a minor issue with an application that I am working on. The problem arises on a particular page where the user can edit a document by dragging modules onto the canvas area. Upon loading the page, JavaScript causes the modules to be ...

Tips for converting text from an HTML input field to a JSON file

After designing a form with four text fields and a submit button, my goal is to save the data into a JSON file upon submission. Additionally, I am looking for a way to display all of the JSON data on my webpage. ...

What could be the reason for the list being undefined even though I explicitly defined it within the <script setup> section of my Nuxt 3 Project?

I am currently working on a Nuxt 3 Project and have created a component that generates a variable amount of elements. When calling the element, it is passed an array as a parameter. In the script setup, I define this array as 'list' and intend to ...

Saving an image in Flask and securely storing it in a local directory

I am looking to implement a functionality where I can upload an image and pass it to the Python code in Flask for local storage. While following a tutorial, I encountered an issue with the query as the request always returned 'No file part': if & ...