Utilizing JavaScript to assign class names to dynamically created elements from objects

I specialize in javascript and am working on adding the CSS class .is-slideUp to each card__item element created from a data object, in order to achieve a sliding-up animation effect.

Although the .is-slideUp class name appears in the console, it does not reflect in the elements. I have attempted using setTimeout but it did not resolve the issue.

The desired outcome is to have each element structured like this:

<div class="card__item is-slideUp">
So that they slide up when scrolling upwards.

If anyone has solutions or suggestions, your input would be greatly appreciated. Thank you!

  const data = [
    {
      content: [
        { card: "Card Title 1", text: "Card Text 1 Card Text 1 Card Text 1" },
        { card: "Card Title 2", text: "Card Text 2 Card Text 2 Card Text 2" },
        { card: "Card Title 3", text: "Card Text 3 Card Text 3 Card Text 3" },
        { card: "Card Title 4", text: "Card Text 4 Card Text 4 Card Text 4" },
        { card: "Card Title 5", text: "Card Text 5 Card Text 5 Card Text 5" },
        { card: "Card Title 6", text: "Card Text 6 Card Text 6 Card Text 6" },
      ],
    },
  ];

  const output = document.querySelector(".card__output");
  async function load() {
    const json = await data;

    for (let i in json) {
      const wrap = document.createElement("div");
      wrap.className = "card__wrap";

      for (let j in json[i].content) {
        const card = document.createElement("div");
        card.className = "card__item";

        const h3 = document.createElement("h3");
        h3.className = "card__title";
        h3.textContent = `${json[i].content[j].card}`;

        const p = document.createElement("p");
        p.className = "card__text";
        p.textContent = `${json[i].content[j].text}`;

        wrap.appendChild(card);
        card.appendChild(h3);
        card.appendChild(p);
      }

      output.appendChild(wrap);
    }
  }
  load();

  slideUp();

  const windowHeight = window.innerHeight;
  const cards = document.querySelectorAll(".card__item");

  function slideUp() {
    window.addEventListener("scroll", function () {
      for (let i = 0; i < cards.length; i++) {
        console.log(cards[i]);
        if ( windowHeight > cards[i].getBoundingClientRect().top + windowHeight / 5 ) {
          cards[i].classList.add("is-slideUp");
        }
      }
    });
  }
  * {
    margin: 0;
    padding: 0;
  }
  header,
  footer {
    height: 200px;
    background: #ccc;
  }
  .card__output {
    width: 100%;
    height: 100%;
  }
  .card__wrap {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    flex-grow: 1;
    margin-left: calc(-10% / 3);
  }
  .card__item {
    /* opacity: 0; */
    transition: all 1s;
    transform: translateY(200px);
    display: flex;
    flex-direction: column;
    width: 30%;
    height: 300px;
    margin-top: 30px;
    margin-left: calc(10% / 3);
    background: #ededed;
  }
  .card__title {
    margin: 1.8rem auto;
    font-size: 2.2rem;
    font-weight: bold;
    text-align: center;
  }
  .is-slideUp {
    background: pink;
    opacity: 1;
    transform: translateY(0);
  }
<header>header</header>
<div class="card__output">
  <!--output data object-->
</div>
<footer>footer</footer>

Answer №1

The issue arises when you attempt to apply a class to an element that is being created asynchronously in a seemingly synchronous manner.

To resolve this, update your javascript code as shown below:

load().then((res) => {
    slideUp();
  });

  function slideUp() {
  const windowHeight = window.innerHeight;
  const cards = document.querySelectorAll(".card__item");  
    window.addEventListener("scroll", function () {

      for (let i = 0; i < cards.length; i++) {
        console.log(cards[i]);
        if ( windowHeight > cards[i].getBoundingClientRect().top + windowHeight / 5 ) {
          cards[i].classList.add("is-slideUp");
        }
      }
    });
  }

Answer №2

To include several classes, simply use the following syntax:

card.className = "card__item is-slideUp";

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

Suspend Coontact-Host Upload of Documents

Is there a way to pause or resume uploading, or resume a broken upload using PHP, JavaScript, or jQuery without having to rely on Java, Flash, or C-type programming? Perhaps utilizing PHP socket functions? ...

Parsing nested JSON files to present data on a webpage

I have a JSON file containing Reddit post titles and their respective scores: { "'JavaFX Simple Inventory Management App - Open source'": 39, "'Creating Formula Dependency Maps from Excel Spreadsheets'": 5, "'CVE-2017-5645 ...

Retrieve a collection of JSON files using a single function

The format of JSON links is as follows: www.example.com/link-number-end-of-link.com.json I need to retrieve multiple JSON link files where the only variable changing is the number in the link. For example, it could range from 10 to 40, with the first ...

What is the best method for exporting the api call results to a csv file while ensuring that each individual response value is contained within its own

Here is the format of my API response: [ { "What time is it?": [ "option_2" ] }, { "When will we go home?": [ "option_1" ] }, { "When is your birthday?": [ "2 ...

Variable assigned by Ajax no longer accessible post-assignment

Recently, I've written a script to fetch data from a SQL database and now I'm in the process of creating a JS wrapper for it. Utilizing certain functions, I call the script and extract information from the DB as soon as it becomes available. var ...

Utilizing FullCalendar for showcasing comprehensive details

I'm a big fan of the fullcalendar plugin and all its amazing features. I want to enhance it by displaying more customized information for each event when in agendaWeek or agendaMonth view. Switching between views is easy, but I need help filtering out ...

Utilizing ConfigurationBuilder to incorporate null values into a list using a json file

As I attempt to insert a list of enums into appsettings.json for later iteration in the code, I encounter an issue. When I include a null value in the list within the JSON file, it does not populate as a null value when loading the Settings from the file. ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (http://www.chartjs.org/docs/). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfull ...

Changing the value in sessionStorage does not trigger the onChange event (Next.js)

When I use a custom hook to load data from session storage into an input field, I noticed that the onChange() function doesn't trigger if I delete the entire content of the input. However, it works fine if I add or delete just one character. This issu ...

What is a more efficient way to search and substitute text in NodeJS?

I am currently working on a task that involves reading a file, passing its contents and multiple arrays to a function, using regex to see if there are any matches, replacing them, and finally updating the file. The code I have put together may not be the ...

Update the DOM if the index of any data elements have been modified

Can Vue.js detect the swapping of array elements in my data object? data: { list: [ 'Foo', 'Bar', 'Test' ] } This is the method I am using to swap entries: swapIndex: function(from, to) { var first = this ...

Developing a webpage that navigates seamlessly without the hassle of constantly refreshing with

I am in the process of creating a website that is designed to run everything within the same file, but I am unsure about how to locate study materials for this project. For example: In a typical website scenario -> If I am on index.php and I click on ...

What sets Vue.js apart, class and staticClass - is there a distinction?

Can someone explain the distinction between class and staticClass in Vue.js render functions? While using Template Compilation, I noticed that the output varies based on what is provided to the HTML class attribute. For instance, when passing a single str ...

Ways to identify if a resize event was caused by the soft keyboard in a mobile browser

Many have debated the soft keyboard, but I am still searching for a suitable solution to my issue. I currently have a resize function like: $(window).resize(function() { ///do stuff }); My goal is to execute the 'stuff' in that function on ...

Replacing values in an HTML file with MySql query results

----- Problem solved, solution below ----- In my HTML file, I have a dropdown menu for various courses listed as follows: <ul> <li class="dropbtn" id="1"> <a href="">first</a> <ul class="dropdown-content"> ...

Adding a value to a JSON array using Bash

I have been working on a bash script to parse a URL into its different components. I am currently facing an issue while trying to add an array value to a key within a JSON object. What I've Tried: The URL that I parsed is: https://bar.foo.com/v2020/ ...

Dynamically retrieving markers from the database based on the most recent timestamp of the last loaded batch

I currently have a database where I store marker locations along with their latitude, longitude, type, and timestamp. Right now, my code loads all markers from the database and displays them on the map with different icons based on their type. However, w ...

The behavior of Datatables varies depending on the screen resolution

In my data table, there are numerous entries with child tables on each row of the main table. I am currently in the process of incorporating this type of functionality into my table, with a few modifications to create a table within the child row. You can ...

Learn the process of uploading a file using FormData alongside multer in node js. Experience the issue of receiving undefined in req.file and { } in req.body

Is there a way to successfully upload a file using FormData along with multer in Node.js? I seem to be encountering issues as req.file shows undefined and req.body displays {}. Check out the HTML code snippet below: <input type="file" name=&q ...

Is the process of adding a new row by duplicating an already existing row dynamic?

I've encountered an issue where a row in a table is not being displayed because the CSS style has been set to display:none. Here's the HTML table: <table class="myTable"> <tr class="prototype"> ........ </tr> </ ...