What is the best way to set up a loop for displaying Chat Bubbles?

Is there a way to create a loop for chat bubbles? I want them to appear on the right when I send a message and on the left when the chat partner replies. How can I implement this loop?

This is the code I currently have:

<div class="Webview">
  <div class="message_container" id="myForm"></div>
  <form class="send_container">
    <input id="textField" type="text">
    <p>
      <input type="button" id="theButton" value="Send Message!" onclick="document.getElementById('myForm').innerHTML=document.getElementById('textField').value" />
    </p>
    <h3>
      <div id="div"></div>
    </h3>
  </form>
</div>

Answer №1

If you're looking to dynamically add messages to the DOM without using loops, there's a simple solution. Instead of continuously appending messages, you can trigger the message addition by pressing Enter on the input field.

Here's a step-by-step guide on how to achieve this:

  1. Retrieve the value from the text input field.
  2. Insert this value into a predefined message template (in HTML) and then append it to the DOM.

To implement this functionality, you can either embed a JavaScript snippet within your HTML or include an external JavaScript file containing the necessary function:

function addMessage() {
  // Perform XSS sanitization
  const $messages = document.getElementById('myForm');
  const $textElement = document.getElementById('textField');
  const newMessage = '<div class="message-balloon">' + $textElement.value + '</div>';
  $messages.innerHTML += newMessage;
  return false;
}
<input type="button" id="theButton" value="Send Message!" onclick="addMessage()" />

If you prefer using jQuery, here's how you can achieve the same functionality within the JavaScript scope:

$("#theButton").off('click').on('click', function(e) {
  e.preventDefault();
  const $messages = $('#myForm');
  const $textElement = $('#textField');
  const newMessage = '<div class="message-balloon">' + $textElement.value + '</div>';
  $messages.html += newMessage;
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="theButton" value="Send Message!" />

I hope this explanation has been helpful. Best of luck with your implementation!

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

Using the HTML video tag to apply different background colors based on the individual machines being

My web application includes a video that is set to play against the same background color as the webpage. However, I am experiencing an issue where the video background appears differently on various machines using the same browser. What I would like to ac ...

What is the best way to apply the addClass method to a list element

I've been searching for a solution to this issue for some time now, and while I believed my code was correct, it doesn't appear to be functioning as expected. HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js ...

Having trouble getting my Win and Lose Divs to display in my IF statement within the Card Game

Currently, I am developing a card game where players are presented with a card generated by the computer. The player has to decide whether the next card will be higher, lower, or equal to the current one by clicking corresponding buttons. if ((playerChoic ...

Difficulty in pinpointing hyperlinks within a styled list

My current challenge involves customizing the color of links within the <li> elements by applying specific classes to the <li> tag. The structure of my HTML is as follows: <div id="sidebar_tall"> <ul> <li class="active_item"> ...

Ensure that the floated element stretches to 100% height in order to completely fill the page

I'm working on achieving a height of 100% for the left sidebar so that it fills the page regardless of the size of the "main" div. Currently, it stops at the normal page height and doesn't expand further. Is there any way to make this work as i ...

My index.html not successfully linking to the CSS file

I'm new to this and still learning, so please bear with me. I'm having trouble linking my CSS file to my index.html document in order to create a black banner at the top of the page. I've tried opening it in both Chrome and Explorer but noth ...

Substitute a single occurrence of the dollar sign with an HTML tag

I have been attempting to insert an HTML tag into a price on my e-commerce website. Specifically, I am looking to add a tag between the "$" and the numerical value (e.g. $5.00), but I am unable to locate the core file where I can place the code between the ...

What is the best way to design a large grid layout using HTML5?

I am aiming to construct a 6 by x grid where the columns retain uniform size based on the width of the outer container (i.e. body). The height should be consistent within each row and adjust according to the content in each cell. Below is my current progr ...

JavaScript is having trouble locating the HTML select element

Having trouble selecting the HTML select element with JavaScript? You're not alone. Despite trying different solutions found online, like waiting for the window to fully load: window.onload = function(){ var opt = document.getElementsByName("prod ...

The width of the Div element is not following the specified dimensions, and it also has an unspecified margin

Check out my code snippet at: http://jsfiddle.net/8z4aw/ I'm trying to create a table-like layout using div elements, but for some reason the browser is not respecting the specified widths and seems to be adding an unwanted right margin. Where is thi ...

Determining the Size and Color of Squares in a Treemap Based on Content with D3.js

I encountered an issue with a treemap visualization. I came across an example that is similar to my situation, which can be viewed here: In the demo, you can see that the size of each square in the treemap is determined by the content size. However, all s ...

How do I initiate PUT and DELETE requests from my HTML code?

I am currently in the process of developing a web application that will manage items within a list. Previously, I used buttons with event listeners and JavaScript functions to handle editing and deleting items. However, I am now transitioning towards build ...

The HTML table printout is missing cells in the first column

Encountered a strange issue with Internet Explorer and Chrome involving a basic HTML table. The table has no layout CSS, 2 columns, no styles, and its width is set to 100%. When attempting to print the table in these browsers, the first cell on the second ...

Placing a list item at the beginning of an unordered list in EJS with MongoDB and Node.js using Express

What I've done: I already have knowledge on how to add an LI to UL, but it always goes to the bottom. What I'm trying to achieve: Add an LI to the top so that when my div.todos-wrapper (which has y-oveflow: hidden) hides overflow, the todos you a ...

To enhance the MUI v5 table row, simply apply a border when the mouse hovers

After working on creating a table with Material UI v5, I encountered an issue where I wanted to add a blue border to the table row when the mouse pointer hovered over it. I attempted several methods and did thorough research, but unfortunately, I was unab ...

Repetitive Anchor IDs and Web Standards Compliance

Today, I encountered the task of converting outdated attributes on a page to make it more XHTML friendly. This led me to consider the anchor tag and its usage: Initially, I had anchor tags in the form of <a name="someName"></a>. However, upon ...

Should I create CSS rules for different screen sizes or should I dynamically render components based on the screen size?

As I delve into learning React, I find myself unsure about the most effective approach to make websites responsive. Currently, I am utilizing Semantic UI React as my CSS Library. While everything displays perfectly on desktop, I encounter some issues when ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

"Upon refresh, the overflow property of the child element is being applied to the window position

In the React app I'm working on, there's a search results page where users can apply filters. These filter selections update the query params in the URL and trigger a re-mount in React. However, I've encountered an issue across different bro ...

Updating the total on the Infusionsoft order form can be achieved using either Jquery or custom code

Is there a way to automatically calculate and update the total amount on the order form based on user input in two quantity fields? The price should increase as the user adjusts the quantity. I've been searching for a solution, but haven't found ...