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?