This JavaScript code enhances your HTML webpage by enabling it to read a selected text file and display its content dynamically. The code utilizes the FileReader API to handle the selected file, checks if it’s a text file, and then renders the content in the designated HTML area. This functionality allows you to effortlessly showcase text files on your webpage, offering a seamless way to share and present textual information.
You can use this code on websites where you want users to interactively view text files. It’s handy for sharing documents, instructions, or any text-based content. One major benefit is its simplicity—users can select a file, and it promptly displays the text on the webpage, making information easily accessible without additional downloads or plugins.
How to Read Text File and Display In HTML Using JavaScript
1. Start by creating an HTML file and include the necessary structure. Copy the following HTML code into your <body>
section. This establishes a basic webpage with a file input element and an area to display text.
<div id="page-wrapper"> <h1>Text File Reader</h1> <div> Select a text file: <input type="file" id="fileInput"> </div> <pre id="fileDisplayArea"><pre> </div>
2. Now, copy the CSS code into your <style>
or external stylesheet. This ensures a clean and visually appealing layout for your file reader.
html { font-family: Helvetica, Arial, sans-serif; font-size: 100%; } #page-wrapper { width: 600px; background: #FFF; padding: 1em; margin: 1em auto; min-height: 300px; border-top: 5px solid #69c773; box-shadow: 0 2px 10px rgba(0,0,0,0.8); } h1 { margin-top: 0; } img { max-width: 100%; } #fileDisplayArea { margin-top: 2em; width: 100%; overflow-x: auto; }
3. Finally, copy the following JavaScript code into a <script>
tag or an external JavaScript file. This script allows your webpage to read and display the content of a selected text file.
window.onload = function() { var fileInput = document.getElementById('fileInput'); var fileDisplayArea = document.getElementById('fileDisplayArea'); fileInput.addEventListener('change', function(e) { var file = fileInput.files[0]; var textType = /text.*/; if (file.type.match(textType)) { var reader = new FileReader(); reader.onload = function(e) { fileDisplayArea.innerText = reader.result; } reader.readAsText(file); } else { fileDisplayArea.innerText = "File not supported!" } }); }
That’s all! hopefully, you have successfully created a simple tool to read text files and display them in HTML. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.