Is there a way to have incoming messages automatically align to the left or right based on the sender, without using the float property?

I am currently working on a webpage where I want the messages sent by different users to appear in a yellow conversation window based on who sent them - user 1 or user 2. I want it to mimic the messaging layout commonly seen on phones, distinguishing between the two users with lighter blue and purple background colors. I am trying to achieve this without using float, so any suggestions other than that would be appreciated. Below is the code snippet:

function Send(ele) {
  var br = document.createElement("br");
  var foo = document.getElementById("conversation");
  foo.appendChild(br);
  var para = document.createElement("label");
  var txt;
  if (ele.id == "btn") {
    txt = document.getElementById("text");
    var node = document.createTextNode(txt.value);
    para.appendChild(node);
    var element = document.getElementById("conversation");
    para.className = 'message';
    element.appendChild(para);
  } else {
    txt = document.getElementById("text2");
    var node = document.createTextNode(txt.value);
    para.appendChild(node);
    var element = document.getElementById("conversation");
    para.className = 'message2';
    element.appendChild(para);
  }
}
body {
  margin: 5% 10% 0% 10%;
  background-color: azure;
}

#conversation {
  width: 100%;
  height: 80%;
  background-color: yellow;
}

.parent {
  white-space: nowrap;
  text-align: center,
}

.user {
  display: inline-block;
  width: 50%;
}

.user2 {
  display: inline-block;
  text-align: right;
  width: 50%;
}

.message,
.message2 {
  display: inline-block;
  width: auto;
  height: auto;
  max-width: 50%;
  word-wrap: break-word;
  color: white;
  background-color: DodgerBlue;
  border-radius: 10px;
  padding: 5px;
  margin: 2px;
  position: relative;
  top: 2%;
}

.message2 {
  background-color: purple;
  text-align: right;
}


/*23*/
<div id="conversation">
  <div class="message">
    <label>On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. </label>
  </div>
  <br />
  <div class="message2">
    <label>On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. </label>
  </div>
</div>
<div class="parent">
  <div class="user">
    <input id="text" type="textarea" />
    <input id="btn" type="button" value="Send" onclick="Send(this)">
  </div>
  <div class="user2">
    <input id="btn2" type="button" value="Send" onclick="Send(this)">
    <input id="text2" type="textarea" />

  </div>
</div>

I have also shared the code on jsfiddle for your reference:

https://jsfiddle.net/pbzqw278/

If you could explain the changes made, especially in CSS, it would be greatly helpful as I am still learning about it.

Answer №1

To achieve this layout, you can apply the following CSS styles: set display: block to both .message and .message2, then add margin-left: auto to .message2.

It is recommended to adjust the max-width to approximately 48%.

You may consider moving some CSS properties from the div to the label element. By doing so, the width of the text will determine the width of the background-color.

Check out the fiddle here

body {
  margin: 5% 10% 0% 10%;
  background-color: azure;
}

#conversation {
  width: 100%;
  height: 80%;
  background-color: yellow;
}

.parent {
  white-space: nowrap;
  text-align: center,
}

.user {
  display: inline-block;
  width: 50%;
}

.user2 {
  display: inline-block;
  text-align: right;
  width: 50%;
}

.message,
.message2 {
  max-width: 48%;
  margin: 2px;
  position: relative;
  top: 2%;
  display: block;
}

.message2 {
  margin-left: auto;
  text-align: right;
}

.message label,
.message2 label {
  display: inline-block;
  border-radius: 10px;
  padding: 5px;
    word-wrap: break-word;
  color: white;
  background-color: DodgerBlue;
}

.message2 label {
  background-color: purple;
}


/*23*/
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="script.js"></script>

<body>
  <div id="conversation">
    <div class="message">
      <label>On insensible possession!</label>
    </div>
    <br />
    <div class="message2">
      <label>On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. On insensible possession oh particular attachment at excellence in. The books
        arose but miles happy she. It building contempt or interest children mistress of unlocked no. </label>
    </div>
    <div class="message2">
      <label>On insensible</label>
    </div>
    <div class="message">
      <label>On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. </label>
    </div>
    <div class="message2">
      <label>On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. </label>
    </div>
  </div>
  <div class="parent">
    <div class="user">
      <input id="text" type="textarea" />
      <input id="btn" type="button" value="Send" onclick="Send(this)">
    </div>
    <div class="user2">
      <input id="btn2" type="button" value="Send" onclick="Send(this)">
      <input id="text2" type="textarea" />

    </div>
  </div>

</body>

Answer №2

To achieve the desired layout, you can utilize flexbox and wrap each message in a row with display: flex;. Then, set the messages to align themselves either at the start or end of the container using align-self: flex-start; and align-self: flex-end; respectively. Here is the modified code snippet:

function Send(ele) {
  var foo = document.getElementById("conversation");
  var rowWrapper = document.createElement('div');
  rowWrapper.className = 'message-row';
  var para = document.createElement("label");
  var txt;
  if (ele.id == "btn") {
    txt = document.getElementById("text");
    var node = document.createTextNode(txt.value);
    para.appendChild(node);
    para.className = 'message';
    rowWrapper.appendChild(para);
    var element = document.getElementById("conversation");
    element.appendChild(rowWrapper);
  } else {
    txt = document.getElementById("text2");
    var node = document.createTextNode(txt.value);
    para.appendChild(node);
    para.className = 'message2';
    rowWrapper.appendChild(para);
    var element = document.getElementById("conversation");
    element.appendChild(rowWrapper);
  }
}
body {
  margin: 5% 10% 0% 10%;
  background-color: azure;
}

#conversation {
  width: 100%;
  height: 80%;
  background-color: yellow;
}

.parent {
  white-space: nowrap;
  text-align: center;
}

.user {
  display: inline-block;
  width: 50%;
}

.user2 {
  display: inline-block;
  text-align: right;
  width: 50%;
}

.message-row {
    display: flex;
    flex-direction: column;
    width: 100%;
}

.message,
.message2 {
  display: inline-block;
  width: auto;
  height: auto;
  max-width: 50%;
  word-wrap: break-word;
  color: white;
  background-color: DodgerBlue;
  border-radius: 10px;
  padding: 5px;
  margin: 2px;
  position: relative;
  top: 2%;
}

.message {
    align-self: flex-start;
}

.message2 {
  align-self: flex-end;
  background-color: purple;
  text-align: right;
}


/*23*/
<div id="conversation">
    <div class="message-row">
        <div class="message">
            <label>On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. </label>
        </div>
    </div>
    <div class="message-row">
        <div class="message2">
            <label>On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. </label>
        </div>
    </div>
</div>

<div class="parent">
    <div class="user">
        <input id="text" type="textarea" />
        <input id="btn" type="button" value="Send" onclick="Send(this)">
    </div>
    <div class="user2">
        <input id="btn2" type="button" value="Send" onclick="Send(this)">
        <input id="text2" type="textarea" />
    </div>
</div>

Answer №3

If your conditional statement includes checking which button triggered the action, you can assign a position to the TextNode accordingly.

To apply CSS styling through JavaScript, you can use the following code:

document.getElementById("myTextNode").style.left = "5px;"; 

Make sure to give the TextNode an ID first, which you can do with JavaScript as well. In case you need a refresher, here's how:

node.id = "someID";

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 image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

The content of InnerHtml does not appear on the screen

I am currently building a web project using HTML and Bootstrap, however, I am facing an issue where my content is not showing up in the browser. Below is the code snippet that I am working with: let str = "" for (let item of r.articles) { s ...

Navigate to a new tab using this.router.navigate

Is there a way to redirect the user to a specific page with ${id} opening in a new tab, after clicking a button in an angular material dialog box? I want to leave the dialog box open while querying the new page. Currently, the redirect happens but not in a ...

Creating a Javascript object from a JSON string

Looking for a way to convert a JSON string into a JavaScript object? You can make use of the following code snippet obtained from the server: JSON String: ["{"title":"Admin Dhaka","href":"#0","dataAttrs":[],"data":["{\"title\":\"BNS HAJI M ...

The dataLayer in Google Tag Manager is failing to trigger the necessary event

Product Purchase Button: <button id="btnBuy" onclick="SendData();" JavaScript function to track product details: <script> var dataLayer = []; dataLayer.push( { 'ecommerce': { 'detail': { 'actionField' ...

Querying MongoDB with Mongoose to find objects in an array based on a specific date stored

I am currently working on constructing a mongoose query to retrieve records that match a specific date. It seems like the query is functioning properly, but I'm not getting any results displayed because the date stored in my array of objects is a stri ...

Discover the element's selector for the event that was triggered using jQuery

In the process of creating a lightweight real-time application, we are utilizing jQuery's event system to facilitate communication between modules. Any changes made in the DOM that affect elements outside the module are achieved through triggering eve ...

Is it possible to adjust the left property following the concealment of an element with JQuery?

My goal is to move an image element using the 'left' property after hiding a div. To achieve this, I am using JQuery's '.promise()' function. Here is my code: HTML code: <div id="outerContainer"> <div id=" ...

Creating a personalized cursor transition with CSS styling

I have an unordered list (ul) with items on each list item (li) having a different cursor. While it works fine, the transition is not smooth. Is there a way to make the transition from the default cursor to a custom image smoother? HTML <section class ...

Issue with multiple dropdowns not functioning in Bootstrap 5

Before you criticize my imports, here are the scripts I am using: <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script ...

The criteria set by jQuery are met

I have developed my own custom form validation for two inputs: one for a phone number and the other for an email address. Additionally, I have integrated two forms on a single page. Here is a snippet of my code: var email, phone; if (email address passe ...

Directive that can be reused with a dynamic item name in ng-repeat

I've developed a reusable directive similar to a dropdown, but this dropdown opens in a modal and is functioning well. The structure of my directive is as follows: <p-select items="deptStations" header-text="Select " text="Select departure..." te ...

Issue with fading hover effect on links is not functioning

I recently implemented a fade link hover effect using the code snippet below: a:link {color:#333333; text-decoration: none; -o-transition:.5s; -ms-transition:.5s; -moz-transition:.5s; -webkit-transition:.5s; transition:.5s;} a:visited {color:#FF0033; ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

Retrieving the identifier from a value within a Symfony controller

One thing I am looking to achieve is to retrieve an Id based on a folder number. Both the Id and folder number (which is unique) are located in the same controller. I input the folder number from a text box and then need to direct the user to a /Id page. ...

Using jQuery to strip inline styling from copied webpage content

When I copy content/paragraph from Wikipedia and try to paste it as code on my webpage dynamically, it ends up with a lot of inline styles. I want the code to be clean and properly formatted in HTML. I have tried several methods, but they remove all the ta ...

Struggling with hashtags and ampersands in Angular when making an HTTP request

Dealing with Special Characters # and & in Angular's http.get() Request URL Take a look at my code first. Angular Service let versionsearch = "&"; let strweeksearch = "%23"; this.http.get(this.apiUrl + 'GetVersionInfo?vehicleVersion=' + v ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

Achieve vertical alignment and responsiveness of elements in primefaces using css techniques

In order to vertically align 2 elements inside an outputpanel, I initially used a margin-top of 3em. However, this method proved to be non-responsive, as shown in the following images: https://i.sstatic.net/yMRXc.png In mobile view: https://i.sstatic.net ...

Using Jquery Ajax to validate login information by submitting an HTML form

Working on a project involving jQuery Ajax, HTML forms, MySQL, and PHP. I have a database with registered users and I want to use a login form to retrieve user information from the database upon submission. However, I'm encountering an issue where the ...