I am having an issue with my DIV not functioning correctly in conjunction with my JS animation. What modifications should I make to

I have a simple JS animation script that fetches data from the

<div class="quiz"> Some content </div>
for animation. When I include this script in my HTML, the animation and other functions such as previous and next work properly. See an example below:

// Your JavaScript animation code
#rect {
  font-weight: 900;
  font-size: 2.5em;
}

#rect .letter {
  line-height: 1em;
}

#quizss {
display:none;
}

.word {
  white-space: nowrap;
}
<div class="quiz">Question-1 : The color of the sky is...?</div>
<div class="quiz">Question-2 : Paper comes from...?</div>
<div class="quiz">Question-3 : How many hours in a day?</div>
<div class="quiz">Question-4 : A Giraffe is a fish?</div>

<div id="rect"></div>

<br>
<Button id="rc" onclick="previous()">previous</Button>
<Button id="rc" onclick="next()">Next</Button>

<br>

If you want to dynamically create divs based on multiline text input using a text box, it may not work with the existing JavaScript animation function. You can check this by adding lines through the text box.

The code for your text box is as follows:

// Your JavaScript code for creating dynamic divs
<div id="rect"> </div>

<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>

If you're looking to integrate the text box data into the existing JavaScript animation, you might need to modify the animation script accordingly. Here's a snippet combining both scripts:

// Combined JS animation and textarea script

// Your combined script goes here
<style>
    #rect {
      font-weight: 900;
      font-size: 1.5em;
      font-family: rr;
    }

    #rect .letter {
      line-height: 1em;
    }

    #quizss {
      display:none;
    }

    .word {
      white-space: nowrap;
    }
</style>

// Include necessary scripts

<div class="quiz">Question-1 : The color of the sky is...?</div>
<div class="quiz">Question-2 : Paper comes from...?</div>
<div class="quiz">Question-3 : How many hours in a day?</div>
<div class="quiz">Question-4 : A Giraffe is a fish?</div>

<div id="rect"></div>

<br><br>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>

<br><br>
<Button id="rc" onclick="previous()">Previous</Button>
<Button id="rc" onclick="next()">Next</Button>

Answer №1

There are a couple of things to consider:

  1. It is not advisable to add the new quiz inside the rect. Instead, create a container for all the quizzes and add them there.
  2. Make sure to update your questions variables every time you add a new quiz.

// Animation script in JS starts here

var question = 0;

var questions = Array.from(document.getElementsByClassName("quiz")).reduce((carry, item) => {
  carry.push(item.textContent.trim())
  return carry;
}, []);

var anim;
var targets;

function prepQuestion() {
  $("#rect").text(questions[question]);

  var textWrappers = document.querySelectorAll('#rect');
  textWrappers.forEach(textWrapper => {
    textWrapper.innerHTML = textWrapper.textContent.replace(/(\S*)/g, m => {
      return `<span class="word">` +
        m.replace(/(-|)?\S(-|@)?/g, "<span class='letter'>$&</span>") +
        `</span>`;
    });
  });

  targets = Array.from(document.querySelectorAll('#rect .letter'));

  anim = anime.timeline()
    .add({
      targets: targets,
      scale: [3, 1],
      scaleY: [1.5, 1],
      opacity: [0, 1],
      translateZ: 0,
      easing: "easeOutExpo",
      duration: 150,
      delay: (el, i) => 20 * i
    });
}

// Initialize
prepQuestion();

function next() {
  anim = anime.timeline()
    .add({
      targets: targets.reverse(),
      scale: [1, 3],
      scaleY: [1, 1.5],
      opacity: [1, 0],
      translateZ: 0,
      easing: "easeOutExpo",
      duration: 50,
      delay: (el, i) => 10 * i
    });

  anim.complete = () => {
    if (question == questions.length - 1) {
      question = 0;
    } // Reset question
    else {
      question++;
    }

    prepQuestion();
  };
}

function previous() {
  anim = anime.timeline()
    .add({
      targets: targets.reverse(),
      scale: [1, 3],
      scaleY: [1, 1.5],
      opacity: [1, 0],
      translateZ: 0,
      easing: "easeOutExpo",
      duration: 50,
      delay: (el, i) => 10 * i
    });

  anim.complete = () => {
    if (question == 0) {
      question = questions.length - 1;
    } // Reset question
    else {
      question--;
    }

    prepQuestion();
  };
}
// Animation script in JS ends here

// Textarea script begins here

const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('rect');
const container = document.getElementById('q-container');
var message = textArea.value;

sendButton.addEventListener('click', function() {
  // Split textarea entries into an array
  let lines = (textArea.value).split("\n");

  // Iterate over each line, create a div/span, and insert it into the DOM
  lines.forEach((line) => {
    let encodedLine = encodeHtmlEntity(line);
    let newElement = `<div class="quiz">${encodedLine}</div>`;
    container.innerHTML += newElement;
    questions = Array.from(document.getElementsByClassName("quiz")).reduce((carry, item) => {
      carry.push(item.textContent.trim())
      return carry;
    }, []);
  });

  // Reset the textarea
  textArea.value = '';

});

function encodeHtmlEntity(input) {
  var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
    return '&#' + i.charCodeAt(0) + ';';
  });

  return output;
}
  #rect {
    font-weight: 900;
    font-size: 1.5em;
    font-family: rr;
  }
  
  #rect .letter {
    line-height: 1em;
  }
  
  #quizss {
    display: none;
  }
  
  .word {
    white-space: nowrap;
  }
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="q-container">
<div class="quiz">Question-1 : The color of !the sky is...?</div>
<div class="quiz">Question-2 : Paper comes from...?</div>
<div class="quiz">Question-3 : How many hours in a day?</div>
<div class="quiz">Question-4 : A Giraffe is a fish?</div>
</div>

<div id="rect"></div>

<br><br>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>

<br><br>
<Button id="rc" onclick="previous()">Previous</Button>
<Button id="rc" onclick="next()">Next</Button>

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

The concept of using the `map` method within a

Hi there, I could use some assistance with a tricky issue I'm facing. My current task involves rendering a cart object that includes product names, prices, and quantities. Each product can have its own set of product options stored as an array of ob ...

JavaScript: How can I remove it when I click anywhere on the webpage with onClick?

A challenge I'm facing involves creating a form with an input field that changes its border color when clicked. My goal is for the border to return to its original color when clicking anywhere else on the page. -HTML <form action=""> ...

VueJS component fails to remain anchored at the bottom of the page while scrolling

I am currently using a <md-progress-bar> component in my VueJS application, and I am trying to make it stay fixed at the bottom of the screen when I scroll. I have attempted to use the styles position: fixed;, absolute, and relative, but none of them ...

Press the button to activate the function

<table class="calc" cellpadding=2> <td><input type="button" class="calc" id="screen" value="0" ></td> <td><input type="button" class="calc" id="screen" value="0" ></td> <tr> </ ...

The jQuery .next() function is applying a class to each element

I am struggling with adding a class to the <a> elements in my Bootstrap 4 Carousel when the slider changes. Currently, my code successfully adds the class .highlight to the next <a> elements, but it adds it to all subsequent elements. Addition ...

How can we use the nth-of-type selector to target a set of eight elements in a

I am trying to style a group of divs in such a way that every set of eight elements will have the same left positioning. Rather than just styling every eighth element individually, I want to apply the styling to groups of eight elements at once. However, ...

Is Jsoup receiving the HTML incorrectly?

Currently, I am utilizing Jsoup to fetch HTML data from a website and attempting to display it in a ListView within my app. Although the application compiles without any errors, clicking the button results in an empty ListView. In my opinion, this issue ...

Calculating the total length of an SVG element using React

Looking to animate an SVG path using React (similar to how it's done in traditional JavaScript: https://css-tricks.com/svg-line-animation-works/), but struggling when the path is created using JSX. How can I find the total length of the path in this s ...

Python Selenium scraping script encountered an issue: Javascript element could not be located

I'm currently practicing my skills in scraping Javascript frontend websites and decided to work on the following site: While attempting to locate two elements using their xPath, I encountered an issue. The first element, the title, I was able to find ...

Why is it that when I click outside of the <html> element, the click event bound to the <html> element is triggered?

const html = document.querySelector('html') const body = document.querySelector('body') body.onclick = () => { console.log('body clicked') } html.onclick = () => { console.log('html clicked') } document. ...

When deployed, Webpack 2.2.0.rc-0 will condense and optimize vendor.js and manifest.js, but will not perform the same action on bundle

I have been troubleshooting why my vendor and manifest files are minified and uglified, but my bundle is not. I am wondering if it could be related to the order of the plugins or perhaps something to do with the CommonsChunkPlugin? Here is the code for my ...

Connect the mileage tracker to a Datalist or grid view component

I recently downloaded the Odometer Sample from , however, I am facing an issue where only the first element in the Datalist is getting the Odometer display, while others are not displaying it. Here is the snippet of code: <script type="text/javascript" ...

Arranging JavaScript object by object properties (name)

Can anyone assist me with my training? I am currently learning JavaScript (Js) and TypeScript (Ts) by working with an external public API. After successfully fetching and displaying my data, I now want to implement sorting functionality. My goal is to sor ...

Clear Input Field upon Selection in JQuery Autocomplete

I've been experimenting with the Azure Maps API to add autosuggestions for addresses in an input field. https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/master/AzureMapsCodeSamples/REST%20Services/Fill%20Address%20Form%20with%20Autosuggest. ...

At times, the jQuery function may fail to execute

Here is a function I have been using to set an iframe height to match its content: $("#MSOPageViewerWebPart_WebPartWPQ1").load(function() { var Height = document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').contentWindo ...

Leveraging Object.assign for updating fields in Firebase documents

Currently, I am working on a website that allows users to create new projects by filling out a form with all the necessary project information. Within this form, there is a file input field where users can upload images and documents. I have successfully i ...

Retrieving the custom attribute value from the chosen option and storing it in a JavaScript variable

I am currently working on a project that involves a country select input, with custom attributes included in the options. My goal is to retrieve the value of the "name" attribute using JavaScript and then append it to a link for further processing. Howev ...

Despite having unique ids, two file input forms are displayed in the same div in the image preview

Running into a minor issue once again. It may not be the most eloquent query, but I'm genuinely stuck and in need of some assistance. I am attempting to showcase image previews of selected files in a file input form. I have a jQuery script that reads ...

The selected items in the Combobox are displaying as [object, Object] instead of their actual String values

Below is the code I have for a ComboBox with a checklist: <sq8:ComboBox runat="server" ID="ComboBox1" CheckBoxes="True" CheckedItemsTexts="DisplayAllInInput" Width="340px" OnClientItemChecked="ShowAlert"><Items> <sq8:ComboBoxItem runa ...

Transmit a targeted header through ajax to Flask

When working on my flask api file (api.py), I encountered an issue with retrieving the header "USER" to establish a connection when a user sends a request. Here is the relevant code snippet: @app.before_request def prepare(): print('Step ...