How to Load DIV Content on Click Only using JavaScript?
Last Updated :
15 Nov, 2024
Improve
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:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Load Content on Click</title>
</head>
<body>
<!-- Button to trigger the content load -->
<button id="loadBtn">Load Content</button>
<!-- Div where the content will be loaded -->
<div id="contentDiv">
<!-- Content will be loaded here -->
</div>
<!-- Link to the JavaScript file -->
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
// Get the button and content div elements
const loadButton = document.getElementById("loadBtn");
const contentDiv = document.getElementById("contentDiv");
// Add an event listener to the button
loadButton.addEventListener("click", function() {
// Load static content into the div
contentDiv.innerHTML = "<h2>New Content Loaded!</h2><p>This is the new content added when the button was clicked.</p>";
});
Output:


Explanation:
- HTML:
- There's a button (
<button>
) that will trigger the action to load content. - The content will be inserted into a
<div>
with theid="contentDiv"
.
- There's a button (
- 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 thediv
to insert new content.
- We first get references to the button and the
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 filecontent.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 adiv
. - For dynamic content, consider using
fetch()
orXMLHttpRequest
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