Web Front-end
HTML Tutorial
How to dynamically read and fade in and out the contents of multiple text files using a jQuery function
How to dynamically read and fade in and out the contents of multiple text files using a jQuery function

This article introduces an efficient and scalable solution: using only one jQuery function and a semantic HTML structure, you can load corresponding txt files for hundreds of buttons, and achieve smooth fadeOut/fadeIn content switching effects, avoiding duplication of code and hard coding.
To bind independent text files (such as file1.txt, file2.txt...) to each of 300 buttons without rewriting functions or HTML 300 times, the key is to decouple data and behavior : inline the file path as a data attribute (data-file) into the button, and the unified event processor reads and performs asynchronous loading.
The following is a recommended implementation that is modern, robust, and easy to maintain:
✅ Recommended writing method: delegate event data attribute driven
<div class="content">
<div class="buttons">
<button class="button" type="button" data-file="file.txt">First</button>
<button class="button" type="button" data-file="file1.txt">Second</button>
<button class="button" type="button" data-file="faq/privacy.txt">Privacy Policy</button>
<!-- Unlimited appending possible without modifying JS -->
</div>
<div class="textBox">
<div class="answerBox">Click Any Question Button</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
// Use event delegation to support dynamically added buttons (more flexible)
$('.buttons').on('click', '.button', function(e) {
e.preventDefault();
const fileName = $(this).data('file'); // Safely obtain data-file value const $target = $('.answerBox');
// To prevent animation confusion caused by fast connection points: ensure that the pre-order animation is completed before executing $target.stop(true, true).fadeOut(300, function() {
$.get(`files/${fileName}`)
.done(function(text) {
$target.text(text.trim()).hide().fadeIn(400);
})
.fail(function() {
$target.text('❌ Failed to load content. Please check the file path.').hide().fadeIn(400);
});
});
});
});
</script>
? Key optimization instructions:
- The data-file attribute replaces onclick : HTML is cleaner and conforms to the principle of separation of concerns; it facilitates subsequent batch generation with JS (such as rendering buttons from JSON configuration).
- Event delegate (.on('click', '.button', ...)) : Even if the button is dynamically inserted later (such as loading through AJAX), it can be automatically bound without re-initialization.
- .stop(true, true) : Clear the unfinished animation queue to prevent flickering or lagging caused by multiple clicks.
- Path splicing security : Use the template string files/${fileName} to clearly agree that all files are located in the files/ directory, which facilitates unified management.
- Error handling.fail() : When the file does not exist or the network fails, friendly prompts instead of silent failure.
- .trim() cleans newlines/spaces : avoid empty lines at the end of txt files causing redundant whitespace.
? Advanced suggestions (for 300 scenarios):
- Configuration-driven rendering : save button metadata as JSON (such as questions.json), and use JS to dynamically generate a button list, completely eliminating the cost of manual HTML maintenance;
- Caching mechanism : cache loaded file contents in memory (such as const cache = {}) to avoid repeated requests;
- Loading status prompt : Temporarily display Loading... or skeleton screen in .answerBox to improve user experience;
- Support Markdown or simple HTML : If you need rich text in the future, you can use .html() instead and cooperate with the sanitize-html library to ensure security.
This solution takes into account simplicity, maintainability and performance. It is written once and adapted for life - whether there are 3 or 300 buttons, there is no need for structural modifications to HTML and JS.
The above is the detailed content of How to dynamically read and fade in and out the contents of multiple text files using a jQuery function. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How to correctly migrate jQuery's drag and drop events to native JavaScript
Mar 06, 2026 pm 05:15 PM
This article explains in detail the key pitfalls when migrating jQuery drag-and-drop logic (such as dragover/dragleave) to Vanilla JS - especially the problem of misuse of e.originalEvent causing dataTransfer failure, and provides directly runnable fixes and best practices.
How to make the images in a div fill with no margins while retaining the inner margins of the text
Mar 07, 2026 pm 10:54 PM
This article explains how to keep the overall padding of the container so that the internal images are displayed close to the edge of the container, while the text content still maintains normal padding - the core is to separate the style scope and achieve precise layout through positioning and box model control.
Solve the problem of unexpected offset of Flex container due to the font size change of the first child element
Mar 09, 2026 pm 08:15 PM
When the first child element of a Flex container dynamically adjusts the font-size, the container will be vertically offset along the inline baseline; while a normal block-level container will change in height due to the linkage between line height and font measurement. The root cause lies in the baseline alignment mechanism of the Flex container. By default, the baseline of the first child is the container baseline. This can be completely solved through vertical-align: top or explicit baseline control.
Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart)
Mar 12, 2026 pm 08:51 PM
This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.
A complete guide to using the keyboard to control the smooth movement of HTML elements
Mar 13, 2026 pm 10:18 PM
This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.
How to dynamically pass HTML form data to analytics.track() method
Mar 13, 2026 pm 10:57 PM
This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.
How to properly override default styles and implement custom CSS layouts in Divi theme builder
Mar 14, 2026 am 12:00 AM
This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.
How to optimize Lighthouse image scoring while maintaining high image quality
Mar 11, 2026 pm 09:39 PM
This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.





