Currently, I am developing a compact web tool to assist editors in creating content by utilizing buttons to insert paragraphs and images. The elements are saved with an ID (beginning at 0 and increasing for each new element) and can be previewed in a div named "preview" that mimics the layout of the final webpage.
I have encountered a puzzling issue where the image always appears below all the paragraphs instead of following the correct order. Although there is likely a simple solution, my limited experience with HTML, CSS, and JavaScript has hindered my ability to find one online. I apologize if this error seems trivial or if the solution has already been discussed elsewhere.
The following code snippet showcases how I render the preview using JavaScript:
// Preview current document status
document.getElementById("previewButton").addEventListener("click", function() {
// Clear
document.getElementById("preview").innerHTML = "";
// Add all elements properly
var section = document.getElementById("preview");
var id = "preview";
for (var counter = 0; counter < element_counter; counter++) {
var type = document.getElementById(counter).nodeName;
// If text element
if (type === "TEXTAREA") {
var paragraph = document.createElement("p");
var text = document.getElementById(counter).value;
paragraph.setAttribute("id", id + counter);
paragraph.setAttribute("class", "flow-text");
paragraph.append(text);
section.appendChild(paragraph);
}
// If image element
if (type === "INPUT") {
var file = document.getElementById(counter).files[0];
var reader = new FileReader();
reader.onload = function(e) {
var image = document.createElement("img");
image.setAttribute("id", id + counter);
image.setAttribute("src", e.target.result);
image.setAttribute("class", "materialboxed responsive-img");
section.appendChild(image);
}
reader.readAsDataURL(file);
}
}
});