Arrange list items dynamically using ajax

I am attempting to adjust the positioning of the scrollable list item depending on whether a message was sent by a user or another party. However, my current method is not yielding the desired results.

I have experimented with adding .css('position', 'right') and including position="right" when calling the div.

Here is an excerpt of my AJAX implementation:


    success: function(data)
    {
        var messages = data['serverResponse'];
        
       $.each( messages, function( name, value) {

           if(value.user === "1")
           {
                $(".message").append("<div class='" + name + "'>" + value.name + "</div>").css(".sentMes");
                $(".message").append("<div class='" + name + "'>" + value.message + "</div>");
                $(".message").append("<div class='" + name + "'>" + value.date + "</div>");
            } else
            {
                $(".message").append("<div class='" + name + "'>" + value.name + "</div>");
                $(".message").append("<div class='" + name + "'>" + value.message + "</div>");
                $(".message").append("<div class='" + name + "'>" + value.date + "</div>");
            }
     });

For the HTML part:

  
  <title>AMessage</title>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
   <script type="text/javascript" src="JavaScript/ThreadsandMessages.js">     </script>
   <link rel="stylesheet" type="text/css" href="AMessage.css">

</head>
<body>
  <header>header area</header>
<nav>
    <ul role="list">
         <li class="thread" role="listitem"></li>
   </ul>
   </nav>

   <nav>
    <ul role="list">
        <li class="message" role="listitem"></li>
  </ul>
  </nav>
 </body>
</html>

Answer №1

"correct" is an invalid value for the "position" attribute. Refer to this link for a list of valid values.

If you use $(".message").append("...");, all your message objects will be added to the same list item with the class "message". To avoid duplicate results, create a new list item for each message as shown in the code snippet below.

To align elements to the right or left within the parent element, utilize the float property. Make sure to combine it with the clear property to prevent items from appearing on the same line.

Instead of using .css() to add a class to an element, use .addClass() to prevent overriding other classes.

var messages = [{
  user: "1",
  name: "John",
  message: "Hi there",
  date: "01/01/2016"
}, {
  user: "2",
  name: "Tim",
  message: "Hey what's going on?",
  date: "01/01/2016"
}, {
  user: "1",
  name: "John",
  message: "Not much",
  date: "01/01/2016"
}];

$.each(messages, function(name, value) {
  var message =
    "<li class='message' role='listitem'>" +
      "<div>" + value.name + "</div>" +
      "<div>" + value.message + "</div>" +
      "<div>" + value.date + "</div>" +
    "</li>";

  $("#messages").append($(message).addClass(value.user === "1" ? "sentMes" : ""));
});
#messages {
  list-style: none;
}

.message {
  float: right;
  clear: both;
  background-color: #BEBCBC;
  border-radius: 5px;
  padding: 10px;
}

.message.sentMes {
  float: left;
  background-color: cornflowerblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<header>header area</header>
<nav>
  <ul role="list">
    <li class="thread" role="listitem"></li>
  </ul>
</nav>

<nav>
  <ul role="list" id="messages">
  </ul>
</nav>

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

Choosing a combination of classes

For my web application, I created checkboxes that control the visibility of windows by toggling classes on elements. My JavaScript code successfully achieves this functionality. $(document).ready(function(){ $('#field').change(function(){ ...

The implementation of display flex is causing issues with the material-ui grid layout

Struggling to implement the grid system from material-ui due to an issue where grid items do not resize when resizing the browser window. The culprit seems to be a parent div with the style property "display": "flex". The dilemma arises from using a mater ...

When the onClick method is triggered, it retrieves a single object from json_encode

Currently, I am using the json_encode method on data extracted from a table. After applying a var_dump to this variable, it reveals three objects: {"id": "5"} {"id": "6"} {"id": "7"} Here's my process: I have an image with an onclick function: < ...

Encountering an incorrect number of parameters for "undefined" during the deployment of a smart contract

I am facing an issue while attempting to deploy my first Voting contract on the testRPC. The error seems to arise from the arguments parameter in the code snippet below. When I tried passing an empty array, it gave an error stating "Got 0 expected 1!". Si ...

Error encountered when using the enter or return key with directive syntax

Newbie Alert I'm encountering something strange while attempting to create a custom directive in AngularJS. When I input this code: myModule.directive('myTab', function(){ console.log('--Inside TAB directive--'); return ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

Transitioning backgrounds in a slideshow

I am attempting to create a unique slideshow effect for my page background by changing the image URL at specific intervals with a smooth fade in and fade out transition. However, I am faced with the challenge of figuring out the best way to achieve this. ...

Tips for subscribing to an Angular Unit Test:

In the process of writing test cases for a component, I first tackled a basic test case to ensure smooth functionality. Initially, I faced Dependency Injection errors and managed to resolve them. The current challenge I am encountering involves mocking API ...

Retrieve the HTML code from a webpage on a different domain

Looking to extract HTML from another domain. Attempted solution: $.get("http://website1.com", function(data) { alert("Data Loaded: " + data); }); (not working) For example, as the owner of two websites: website1.com website2.com Now, the goal is to ret ...

Tips for anchoring a row to the bottom of a Bootstrap webpage

After working with bootstrap, I am looking to position the last row of the page at the bottom in a fixed and responsive size manner. ...

Utilizing jQuery to access data retrieved from ajaxStop

Seeking help on retrieving the json data returned from ajaxStop... I have tried accessing the data property within the event object, but it shows as undefined even though the data is being returned correctly... Cheers, Anthony UPDATE: Upon using Succes ...

Enhancing Image Upload with Ajax/JavaScript: Generating Multiple Previews

I've been experimenting with an Ajax image uploader that I found on this website. Currently, I have managed to create duplicate preview images: one displayed under the input field and the other elsewhere on the page labeled as "this what you chose". H ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

How to include a Partial View or Child Page into a Master Layout using jQuery/Ajax in ASP.NET MVC

Currently, I am in the process of working on a CRM Admin panel that utilizes a left-hand side panel for navigation to various pages. Within this panel, there are buttons such as Home, About, and Contact. To streamline the layout, I have implemented a mast ...

Ways to ensure the jQuery Sticky Float plug-in responds dynamically to updates on the page

Recently, I came across the amazing 'stickyfloat' plug-in(http://plugins.jquery.com/files/stickyfloat_0.htm) for jQuery that I'm considering using for a project. The main goal is to have a fixed panel on the right side of the page as the con ...

CSS - Ensuring that the height of one div extends all the way down to meet another div

I'm facing an issue with two divs in my design. One of them contains a checkbox and the other has text which can vary in size - sometimes it's small, sometimes it's large. When the text in the second div is big, the box on the left extends a ...

WebGL Tips: Resizing an object using vector multiplication, achievement showcased (see image)

I'm currently exploring methods to scale an object without taking into consideration its local rotation. While I have achieved some success using morph animation, I am searching for a more dependable solution. ...

Utilize webpack to import functions from separate files

I am looking to streamline the process of importing and using functions from a different file. Ideally, I would like to simply call these functions by their name without any extra prefixes or naming conventions. However, I am aware that using eval() can po ...

Is it possible for the req.url path in expressjs to represent a different URL?

Recently, I discovered some suspicious requests being sent to my node-express server. In response, I created a middleware to record the request URLs. After logging these requests, I noticed that most of them started with '/', but there were also ...

Struggling to increment the badge counter in a React Typescript project

I'm a bit unsure about where to apply the count in my Badge Component. The displayValue should include the count, but I'm struggling with how to implement it. UPDATE: The counter is now in place, but when I decrease the count and it reaches 0, t ...