I'm trying to build a notary of sorts. This notary will have different buttons and with the press of each button a different message of plain text will display in a custom div. I want all buttons to display different messages, but display them in the same div and when a different button is pressed, the former message will fade away and the new message will fade in.
I have a basic understanding of the jQuery.get() and this is my JS and HTML code that I've used to read/display one file in that custom div by clicking the button labeled "First":
function Answer() {
jQuery.get("file.txt", function(text) {
$(".answerBox").text(text);
})
};
<body>
<div >
<div >
<button type="button" onclick="Answer()">First</button>
<button type="button" onclick="Answer()">Second</button>
</div>
<div >
<div >Click Any Question Button</div>
</div>
</div>
</body>
The issue comes when clicking the button labeled "Second", it reads the same file.txt and displays the same message. I am puzzled as to how I can expand this single function to encompass all 300 some odd buttons I will need and yes, each button will display a different message and will be tied to a different txt file. I really don't want to rewrite this small function 300 some times and I know there is a better way I just cannot find it.
CodePudding user response:
Here's a revised version of your code based on what you described:
function displayAnswer(file) {
jQuery.get(file, function(text) {
$(".answerBox").fadeOut(function() {
$(this).text(text).fadeIn();
});
})
};
<body>
<div >
<div >
<button type="button" onclick="displayAnswer('file1.txt')">First</button>
<button type="button" onclick="displayAnswer('file2.txt')">Second</button>
</div>
<div >
<div >Click Any Question Button</div>
</div>
</div>
</body>
In this version, we pass the file name as an argument to the function displayAnswer()
, which allows us to read and display different files with one function. The fadeOut()
and fadeIn()
methods are used to create a fade effect when changing the text.
CodePudding user response:
So I've just asked this question, but I've been digging a bit more and I think I may have found something useful. I've rewritten my JS function and HTML as:
`function Answer(file) {
let list = [];
url = "files/" file
list.push(url);
if (list.includes(url)) {
jQuery.get(url, function(text) {
$(".answerBox").fadeOut(() => {
$(".answerBox").text(text);
})
$(".answerBox").fadeIn(2000)
});
<div >
<button type="button" onclick="Answer('file.txt')">First</button>
<button type="button" onclick="Answer('file1.txt')">Second</button>
</div>
` This kinda solves my initial problem, but now I will need to make 300 instances of buttons in HTML. Is there any other way or is this the best I can do with what I know?