Avoiding divs from crashing into each other

I've developed a game feature that allows users to chat. Each message is displayed as an absolute positioned element in the body with user x position set as the "left" CSS property. These messages are animated to move to the top of the screen. I want to ensure that they do not overlap, either vertically or horizontally.

Here's an illustration:

https://i.sstatic.net/hxYF4.gif

The messages should be displayed one after another without overlapping.

I attempted to use a jquery each() function and subtract 60 pixels from the current message position. Here's my code:

var Speech = {
    History: [],
    New: function(user, text, int) {
        var pos = getUserPosition(user).x + 18;
        var speech = HTML.Speech.split('\n');
        var maxInt = speech.length - 1;
        if (int <= maxInt) {
            var html   = speech[int];
            var random = Rand(10);

            Speech.pushThemUp();

            /** append here ect...
            set left position...
            $('#speech' + random).css("left", nLeft + "px"); **/
        }
    },
    pushThemUp: function() {
        $('.speech').each(function(i, obj) {
            var newTop = parseInt($(this).css('top')) - 60;
            $(this).css('top', newTop+'px');
        });
    },
    Listener: function() {
        var int = setInterval(function() {
            $('.speech').each(function(i, obj) {
                if(parseInt($(this).css('top')) < 0) {
                    $(this).remove();
                } else {
                    var newTop = parseInt($(this).css('top')) - 10;
                    $(this).animate({'top': newTop+'px'});
                }
            });
         }, 1000);
    },
    getHistory: function() {
        return Speech.History;
    }
};
Speech.Listener();
module.exports = Speech;

However, this approach does not prevent message collisions as seen in the example above.

How can I resolve this issue?

Please note: in the provided example, the Speech.Listener() was not invoked.

EDIT: After reconsideration, I believe that my current method of iterating over the .speech class and adjusting the top position is effective, but why are the movements animated? In the gif provided, the pushThemUp function should directly adjust the position without animation. How can I address this?

Answer №1

I developed a piece of code that showcases messages moving upwards on the screen. As the available space fills up, a scrollbar will appear.

var box = document.getElementById("box");
var topp = 3;

function post(str) {
  var obj = document.createElement("div");
  obj.className = "chatObj";
  obj.innerHTML = str;
  box.appendChild(obj);
  box.appendChild(document.createElement("br"));

  var width = obj.clientWidth;
  var height = obj.clientHeight;
  obj.style.marginLeft = (box.clientWidth / 2 - width / 2) + "px";

  var x = 15;
  obj.style.top = (box.clientHeight - x - height) + "px";

  var interval, ctop;
  interval = setInterval(function() {
    x += 4;
    console.log(ctop, topp);
    ctop = box.clientHeight - x - height;
    obj.style.top = ctop + "px";
    if (ctop <= topp) {
      obj.style.top = topp + "px";
      topp += height + 6;
      clearInterval(interval);
    }
  }, 5);
}

setTimeout(function() {
  post("Hi!");
}, 500);

setTimeout(function() {
  post("Trollolo!");
}, 1500);

setTimeout(function() {
  post("Lorem ipsum dolor sit amet, timeam aliquando ei cum, putent possim in usu, at causae pericula petentium has. In mea legere salutatus voluptaria. No vix ancillae accusata. Nec meis probo noster eu, ius no quas audire.<br><br>Qui quem nominavi ei. Pri nisl eirmod id. Has cetero vocent abhorreant no, at mei altera expetendis. Has id novum aeterno salutatus.<br><br>Prompta offendit et eos, eos an admodum comprehensam, ex velit doming dolorem mei. At has dolor alterum laoreet, id duo tollit libris contentiones. An mel recteque omittantur dissentiet, ex nam novum iuvaret. Per id alterum habemus gubergren.<br><br>Nulla possim mea in. Vis et postulant constituam. Viris vulputate vituperatoribus eu usu, wisi meis ex his. Prompta accumsan cum et, possim eligendi omittantur sed id. Eos ad nemore integre recusabo, agam doctus viderer ei pri, cu eius nonumes senserit vis. Qui iudico causae te.<br><br>Eam ne mandamus evertitur, case adversarium neglegentur duo ex, no cum nominati forensibus. Et vel putant deleniti. Illum aliquando voluptatibus per no, ei quo albucius phaedrum. Cu lorem appetere percipit sed, ubique epicuri ad eos, te eos diam nusquam persecuti. Eu qui meis illum eleifend, eam veniam vivendo no, nisl fierent in quo.");
}, 2500);
#box {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: tomato;
  overflow: auto;
}
#box .chatObj {
  position: absolute;
  display: inline-block;
  max-width: 80%;
  background-color: white;
  border-radius: 2px;
  padding: 3px 6px;
  margin: 3px 0;
  box-shadow: 0 0 2px 1px rgba(0, 0, 0, 0.1);
  font-family: Arial, sans-serif;
  font-size: 14px;
}
#box .chatObj::after {
  display: block;
  position: absolute;
  content: ".";
  color: transparent;
  height: 6px;
}
<div id="box"></div>

Answer №2

By utilizing position: relative along with a wrapper element styled with display: block, achieving your desired outcome can be easily accomplished without the need for collision detection. Simply calculate the initial top value by subtracting the player's position from the bubble's original top position (since using position: relative will cause bubbles to stack in the DOM below each other).

For a visual demonstration, check out this straightforward jsfiddle example. https://jsfiddle.net/username/example123/

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

Can you explain the functionality of the execCommand "insertBrOnReturn" feature?

I ran some code in Chrome and encountered an unexpected behavior: document.execCommand("insertBrOnReturn", false, true); http://jsfiddle.net/uVcd5/ Even though I've tried setting the last parameter to true or false, the outcome remains the same: ne ...

how to use beautifulsoup to insert a new tag within a text block

When a browser encounters the text www.domain.com or http://domain.com/etc/ within an HTML text section, it automatically converts it into <a href="http://www.domain.com">www.domain.com</a> or <a href="http://domain.com/etc/">http://domai ...

Show and hide components in React by simply clicking on them

I'm looking to achieve the following: If the component is visible, clicking away from it should hide the component. If the component is hidden, clicking on it (or any area that it would occupy if visible) should show the component. Is there a way to ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

The latest alpha version of Angular2 Material Design (alpha.9-3) encountered a "404 not found" error when trying to access @angular

After carefully following the steps outlined in the angular material2 Getting Started guide to install @angular/material, I made updates to package.json, app.module, and systemjs.config using Atom. Specifically, I added the line '@angular/material&apo ...

Placing two parent flex containers on top of each other

I'm in a situation where I have two .container elements, both set at a height of 50%. Within these containers are the child divs .element, which belong to their respective parent divs .container. The problem arises when applying media queries with f ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Disable, Hide, or Remove Specific Options in a Single Dropdown Selection

A challenge I am facing involves creating a form with multiple select options that need to be ranked by the user from 1-8. However, I am encountering some difficulties in hiding, removing, or disabling certain select options. Below is an excerpt from my f ...

I am facing difficulties in installing the necessary node modules for my Angular project

After attempting to run npm install, an error message is displayed towards the end: error syscall unlink 22396 error The operation was rejected by your operating system. 22396 error It's possible that the file was already in use (by a text editor or ...

Is it possible to achieve avoidance of width calculation using only CSS?

Check out this link for more information. For a working version, visit: this site. The issue here is that Angular is calculating the width of the slider when the directive is processed, but since the item is not visible, it has no width. The labels on th ...

Performing multiple actions with the same key in Jquery based on their position

My goal is to enable users to scroll through a list by pressing the down arrow key, and I have successfully implemented this feature. In addition, users should be able to load the next list when they reach the end of the current list. This functionality h ...

Using AJAX in Classic ASP to submit a form via a POST request

My code in TEST.ASP looks like this: <HTML> <HEAD> <SCRIPT src="ajaxScript.js" type="text/javascript"></SCRIPT> </HEAD> <BODY> <FORM action="action_page.asp" method="post"> First Name:<BR> ...

The identical animation is experiencing delays in various directions

Having an issue with my image slider - when clicking on the previous image button, the animation takes longer compared to when clicking on the next image button, even though the animation duration is set to be the same for both. Any idea why this might be ...

Adjust the Container's gutters in MaterialUI according to screen sizes

I am trying to adjust the gutters for different screen sizes in my project. I want to turn off the gutters for xs, sm, and md, but have them enabled at xl and larger. Despite following the API documentation, it doesn't seem to be working as expected. ...

Ensuring Compatibility of jQuery with Internet Explorer

Attempting to display a long and intricate source code, I have decided to share a link to the problematic page instead. In Google Chrome or newer Firefox versions (5 or 6), the jQuery in this script functions as intended. However, issues have arisen in IE ...

Navigate through a JSON data structure containing nested arrays

Does anyone know an effective way to loop through a JSON object that contains two or more nested arrays? The goal is to extract the values from each array without including key-value pairs in the output. {"Obj": ["array 0", ["nested array 1"], ...

Is there a method or API available for interacting with an <object> that is currently displaying a video?

Yay, I figured it out! I've been using video.js to play videos on a website that needs to work offline too. Unfortunately, using flash is not an option due to compatibility issues. So, I decided to write my own fallback solution. For Internet Explor ...

Troubleshooting problem with RadEditor rendering (LI)

I'm experiencing an issue with Telerik RadEditor specifically in IE (not Firefox, Chrome, or Safari). It seems like there may be a conflicting css style causing the problem, but I'm not sure which one it is even after deleting several styles. I h ...