Transforming the text to a new line

I have been attempting to format lengthy texts from a JSON file, but I haven't been successful. The text keeps displaying as multiple sections within a single response, which can be seen in the image below. I've tested solutions like word-break and overflow-wrap, but none of them seem to resolve the issue... Can anyone provide assistance?

Below is my script:

$(document).ready(function () {
  $("form").on("submit", function (event) {
    var rawText = $("#text").val();
    var userHtml =
      '<p class="received-msg-inbox"><span class="received-msg-inbox-p">' +
      rawText +
      "</span></p>";
    $("#text").val("");
    $(".msg-page").append(userHtml);

    $.ajax({
      data: {
        msg: rawText,
      },
      type: "POST",
      url: "/get",
    }).done(function (data) {
      var botHtml =
        '<p class="outgoing-chats-msg" ><span class="outgoing-chats-msg-p" >' +
        data +
        "</span></p>";
      $(".msg-page").append($.parseHTML(botHtml));
    });
    event.preventDefault();
  });
});

I have experimented with CSS styles like overflow-wrap, but they have not yielded the desired result. I anticipate the response to appear within a single field and wrap onto different lines based on the length of the text.

Answer №1

Your script does not seem to be the root cause of the issue at hand; it appears to lie within the CSS. Without access to your CSS code, it is evident from the image that the text is not wrapping correctly when it reaches its maximum width. I have replicated your scenario and attempted to propose a solution.

In my opinion, the problem may stem from a lack of utilizing the white-space or word-wrap property. To achieve the desired outcome, you should implement the following CSS:

.received-msg-inbox-p, .outgoing-chats-msg-p {
  white-space: pre-wrap;      /* CSS3 */
  white-space: -moz-pre-wrap; /* Firefox */
  white-space: -pre-wrap;     /* Opera <7 */
  white-space: -o-pre-wrap;   /* Opera 7 */
  word-wrap: break-word;      /* IE */
}

Implementation:

.chat-container {
  display: flex;
  flex-direction: column;
  width: 600px;
  font-family: Arial, sans-serif;
}

.chat-message {
  max-width: 80%;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 10px;
}

.other-person {
  align-self: flex-start;
  justify-content: flex-start;
  background-color: #ddd;
}

.you {
  align-self: flex-end;
  justify-content: flex-end;
  background-color: #0b93f6;
  color: white;
}

.chat-message p {
  margin: 0;
  white-space: pre-wrap;
  white-space: -moz-pre-wrap;
  white-space: -pre-wrap;
  white-space: -o-pre-wrap;
  word-wrap: break-word;
}
<div class="chat-container">
  <div class="chat-message other-person">
    <p>Hello! This is a long message from another person in the chat. It should wrap onto the next line if it's too long for the chat bubble.</p>
  </div>
  <div class="chat-message you">
    <p>Hi! This is a long message from you in the chat. It should also wrap onto the next line if it's too long for the chat bubble.</p>
  </div>
</div>

I trust this information proves beneficial.

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

I encountered an issue while attempting to connect to my MySQL database using my Express API endpoint: error message "connect ECONNREFUSED 127.0

I am currently in the process of developing a web application for a bootcamp using Express and MySQL. I have set up a route to handle a GET request to an endpoint which is supposed to query my MySQL database table and retrieve all records. My intention is ...

Console warning in Next.js: "The 'style' property did not match."

Currently working on a website with Next.js, I've encountered a red color warning in the console related to the Image component from 'next/Image'. Unsure of the reason for this warning, I'm seeking to resolve it to ensure the project&ap ...

After clicking a button in AngularJS, how can you retrieve one of the two JSON files and store it in a $scope variable?

For instance, You have two JSON files: Json file #1: [{colorname:blue},{colorname:blue}] Json file #2: [{colorname:red},{colorname:red}] Within the controller, there exists a variable called $scope.color In the HTML code, there are two buttons named " ...

Leveraging CasperJS in a typical JavaScript script

I am currently working on a NodeJS project that involves integrating CasperJS. However, I have encountered an issue where the 'casper' module cannot be located. In an attempt to resolve this, I decided to npm install spooky --save based on some s ...

Creating a versatile menu component: A step-by-step guide

One of my current projects involves designing a menu screen component that must be user-friendly and easily customizable. The component will consist of various options displayed in list form. const options = [ { text: 'Option 1', }, { ...

Reasons Behind Slow Unmounting of React Components

In my current project, I have implemented a component that wraps multiple ReactList components. The ReactList component features infinite scrolling, meaning it only loads what is currently in the viewport. There are two modes available - simple and uniform ...

Connect the input field to a dictionary

Here is an input field: <input id="DeviceId" class="form-control deviceCatalog" data-bind="value:DeviceTemp, valueUpdate: ['blur']" required /> This input is connected to the following viewModel: var ViewModel = f ...

How can I distinguish the search results from the while loop section at the bottom of the page?

One issue here is the footer's margin position being influenced by the results of the while loop. To see the problem more clearly, visit this link: Below is the code snippet: <div id="print_output1"> <?php $co ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

What is the process for triggering an unordered list when I click on a table data cell within the Hospitals category?

Hi there! I need help with writing a JavaScript function for Hospitals in the code below. When I click on Hospitals, I want to display the values in the unordered list. Expected output: Hospitals--->onclick Bangalore| salem |Goa| Mangalore| Visakhapat ...

Tips for creating an operation within a JSON document?

Today, I am attempting to customize the appearance of my audiobook list. However, when trying to add an aspectRatio key-value pair to each object in my JSON file, I encountered an error. https://i.stack.imgur.com/Qb3TX.png https://i.stack.imgur.com/qTkmx. ...

Using Google Maps: How can I trigger an InfoWindow to open by hovering over a link?

Trying to figure out how to make the "info window" on my map pop up when hovering over a corresponding link in the list of points. Currently, you have to click on a point to see the information. Any suggestions on how to achieve this while ensuring that al ...

php After the ajax request, the array_push function is failing to add values to the

I am having trouble with my ajax and php implementation. I want to append an array every time an ajax call is made, but it doesn't seem to be working. Here are the codes I am using: $('#multiple_upload_form' +count).ajaxForm({ ...

Unable to change background-image as intended

Here is an example of my HTML code with an initial background image: <div id="ffff" style="width: 200px; height: 200px; background-image: url('/uploads/backroundDefault.jpg')">sddsadsdsa<br>dffdsdfs</div> Everything seems to b ...

Creating a dynamic canvas with a three-dimensional model using three.js: A step-by-step guide

I'm currently developing a website where I have integrated a canvas element to display a 3D object (specifically, a cube) using three.js. The canvas is housed within a div, following the guidelines found in various documentation. The issue arises wh ...

What is the proper way to link an image in a nuxt project?

I am working on a modal in the app.html file of my Nuxt project that prompts Internet Explorer users to switch to another browser. The modal includes links to three different browsers for download. Although the modal is displaying correctly, I keep encount ...

Using CSS transitions to animate elements with specified opacity values

My goal is to transition buttons from opacity 0 to opacity 1 with a delay, but I am facing an issue. Some of these buttons have the "selected" class which gives them an opacity of 0.35. However, when the transition starts, the buttons with the "selected" c ...

Is it possible to update the content page without having to refresh the master page?

Our website features a Master page with main menu options and corresponding sub menus. When a user clicks on a main menu item, the relevant sub menus should be displayed. After clicking on a sub menu, the content page should update without having to refr ...

Exploring the process of transferring a variable from Frontend to Backend via a GET API in ReactJS with an Express API

When working with my freight Shipment table, I need to access the email of the logged-in user in order to perform some frontend tasks. However, I am struggling to retrieve this information using the Axios.get() method and use it to query my MySQL DB. In t ...

Is it possible to conceal the contents of a details tag without using a summary tag?

I'm looking for a way to hide the details tag without the summary. In my code, the summary is only visible when a condition [isvisible == false] is met. However, even when the summary is not visible, the details keyword is still shown and I want to hi ...