![]() |
VOOZH | about |
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.
Output:
<button>) that will trigger the action to load content.<div> with the id="contentDiv".div where the content will be loaded.addEventListener to detect a click on the button.innerHTML of the div to insert new content.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:
fetch() function makes an HTTP request to load content from the file content.txt (you can replace it with your file path or URL).div. If there's an error (e.g., the file doesn't exist), an error message is shown instead.innerHTML of a div.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