What is the best way to present both paragraphs and images from a div in a sequential order

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);
      }
   }
});

https://i.sstatic.net/KhSpx.png

Answer №1

It seems like this approach could be effective. Testing is difficult without access to your code, but the general idea is to isolate certain variables to represent specific instances before adding the image element to the DOM. The reader.onload function should still run asynchronously.

If the type equals "INPUT", {

    (function() {
        var file = document.getElementById(counter).files[0];
        var reader = new FileReader();
        var image = document.createElement("img");
        image.setAttribute("id", id + counter);
        image.setAttribute("class", "materialboxed responsive-img");
        section.appendChild(image);

        reader.onload = function(e) {
            image.setAttribute("src", e.target.result);
        }

        reader.readAsDataURL(file);
    }());
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to style a date and time object using angularjs

What is the best way to convert a PHP datetime object to the format "May-27-1990"? ...

Tips for establishing expiration and validation rules for JSON web tokens

There is an issue with the token expiration time calculation. The comparison of both dates shows that the token would expire in around 17 hours, which is incorrect. It should actually only be 1 minute longer from the time of generation. I would greatly ap ...

Change a JavaScript object into an array with different options while still maintaining the keys

I am attempting to transform the following JavaScript object: image_uploads: [ 0: { upload_id: 50, }, 1: { upload_id: 51, }, 2: { upload_id: 52, }, ] Into separate entries using this structure for inclusion in the body of a POST r ...

Are routes in Next.js easy for search engines to crawl?

Currently, I am developing a movie application using NextJS to enhance my skills. The homepage features each movie's title and a brief description. When a user clicks on a movie, they are taken to a dedicated page that showcases more details about the ...

PHP reCAPTCHA integration with AJAX functionality

I have been attempting to integrate a reCAPTCHA into my PHP contact form using AJAX. The goal is to present the user with the reCAPTCHA challenge and allow them to input it. If the input is incorrect, an error message should be displayed without refreshing ...

Bringing a React Context Back to its Original State

The default state of a React Context is defined as: export const defaultState: UsersState = { isModalOpen: false, isCancelRequest: false, companyId: 0, users: [] }; After cancelling the modal, the goal is to reset the state back to its default va ...

Difficulty sending a parameter to the onClick function of a React Button

I'm struggling with passing parameters to my callback function when clicking a material-ui button. Unfortunately, the following approach is not yielding the expected results. const fetchData = async (param) => { } <Button onClick={fetchData(&a ...

Issues with implementing Dark mode in TailwindCSS with Nuxt.js

After spending a couple of days on this, I'm still struggling to get the dark mode working with Tailwind CSS in Nuxt.js. It seems like there might be an issue with the CSS setup rather than the TypeScript side, especially since I have a toggle that sw ...

What could have caused this issue to appear when I tried running ng build --prod?

Issue encountered while trying to build the ng2-pdf-viewer module: An error occurred in the webpack loader (from @angular-devkit/build-optimizer) with the message: TypeError: Cannot read property 'kind' of undefined. This error is related to A ...

Explore accessing a PHP array with multiple dimensions using Jquery Ajax

I have a PHP script that runs a SQL query on my MSSQL Server instance and returns a good result. Now, I'm attempting to manipulate the result using $.ajax in jQuery, but it seems that accessing fields in an object table via "Object.field_name" is not ...

Receiving a `combined` error when updating Meteor isopacket - sourcemapConsumer.destroy function is not recognized

Whenever I attempt to update or create a project using Meteor version 1.9 and above, I encounter the following error: Errors prevented isopacket load: While loading isopacket `combined`: C:\Users\USER\AppData\Local\.meteor\p ...

Experiencing difficulties with Magento operations

Currently facing an issue while attempting to set up Magento on my server. I have transferred all files from another server to mine, but now encountering an error. Could this be related to the symlinks I generated or is it caused by something else? Encoun ...

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

Transferring SetState from a parent component to a child component in React Native

When working with React js, passing setState from parent components to child components is done like this. However, in React Native setABC is undefined. What is the recommended approach for achieving similar functionality in React Native? Parent.js: funct ...

What's the most effective method for setting up this header using the flex grid system?

I have been able to arrange the logo, search bar, and text in different columns, but I'm struggling to figure out how to position the <nav> below the search bar while maintaining the height consistency with the logo. #outer {} #logo { ...

Encountered an error in Next JS and Graph QL where attempting to destructure the property 'data' from an undefined intermediate value

I am encountering an issue while attempting to make a Apollo request to the SpaceX API. I am receiving a 500 (Internal Server Error) and also at getStaticProps. It's unclear whether this is a syntax problem or an error in my method of implementation. ...

No code is appearing on the page, just a blank space

Whenever I visit this page on the web, the screen shows up as empty and I've encountered similar issues with other JavaScript pages that I've created. This makes me wonder if there might be a missing piece of code or something else causing the pr ...

Incorporating HTML within PHP

I'm struggling with the following issue: after this, I end up with a blank page. Here is the code snippet in question: I am attempting to use HTML within PHP and then PHP again within HTML. The rest of the code is functioning correctly. If I replace & ...

Begin dynamic grid items from the left side

Is there an easy way to solve this problem with CSS Grid and dynamic items placement? I'm still learning the ins and outs of CSS Grid and could use some guidance. When my layout has many items, everything is fine: https://i.sstatic.net/Z2aX0.png Ho ...

Tips for changing the style ID depending on the variable value

Currently, I am exploring the possibility of switching CSS styles using jQuery through a simple if condition. Is there an easy method to switch styles based on IDs? In my case, I have two CSS blocks each with different IDs. Here is an example: <style ...