VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-load-div-content-on-click-only-using-javascript/

⇱ How to Load DIV Content on Click Only using JavaScript? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Load DIV Content on Click Only using JavaScript?

Last Updated : 15 Nov, 2024

To load content into a div when a button or any other element is clicked using JavaScript, you can follow these simple steps. You can either load static content or fetch data from an external source using AJAX (for more advanced usage). Below is a basic example to load content into a div when a button is clicked.

Basic Example: Loading Static Content on Click

HTML Structure:

JavaScript (script.js):

Output:

πŸ‘ Screenshot-2024-11-15-163745
Output
πŸ‘ Screenshot-2024-11-15-163900
Onclick

Explanation:

  • HTML:
    • There's a button (<button>) that will trigger the action to load content.
    • The content will be inserted into a <div> with the id="contentDiv".
  • JavaScript:
    • We first get references to the button and the div where the content will be loaded.
    • We use addEventListener to detect a click on the button.
    • When the button is clicked, we change the innerHTML of the div to insert new content.

Example: Loading Content from a File or External Source

If you want to load content from a file (e.g., a text file or a JSON file) when the button is clicked, you can use fetch() or XMLHttpRequest. Here's an example using fetch() to load text content from a file.

Updated JavaScript (script.js) to load external content:


Explanation for External Content:

  • Fetch API: The fetch() function makes an HTTP request to load content from the file content.txt (you can replace it with your file path or URL).
  • Handling the Response: When the content is successfully fetched, it’s inserted into the div. If there's an error (e.g., the file doesn't exist), an error message is shown instead.

Conclusion:

  • For basic content changes, you can simply modify the innerHTML of a div.
  • For dynamic content, consider using fetch() or XMLHttpRequest to load content from external files or APIs.

This approach will make sure the content inside the div is updated only when the button is clicked

Comment
Article Tags: