Colors of names in a Javascript chat

Asked

Viewed 123 times

1

I’m starting to program, and a problem has arisen. I need to develop a kind of extremely simple chat, just indicating the name and the message, without communication with other computers, just appear the name typed and the message. But I need each name to receive a random color and whenever the name is the same the color is the same too. For example: Luiz receives the color blue, whenever Luiz writes something his name will be in blue.

Below are the html, css and javascript codes.

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Aula 09 - Chat</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="aula09-atividade.js"></script>
    <link rel="stylesheet" type="text/css" href="aula09-atividade.css">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css"/>
</head>
<body>
    <div id="principal">

        <div id="cabecalho">
            <h1 id="chat">CHAT</h1>
        </div>

        <div id="nomecss">
            <input class="form-control" type="text" id="nome" placeholder="Nome">
        </div>

        <div id="mensagemcss">
            <textarea class="form-control" id="mensagem" placeholder="Mensagem"></textarea>
        </div>

        <div id="botao">
            <button id="btEnviar" class="btn btn-danger">Enviar</button>
        </div>

        <div id="tabelacss">
            <table id="tabela"></table>
        </div>

    </div>

</body>
</html>

CSS

#principal{
    margin: 10px 120px;
    padding: 10px;
    width: 520px;
    background: #086A87;
    border: 1px solid #A9D0F5;
}

#cabecalho{
    width: 500px;
    text-align: center;
}

#chat{
    color: white;
    height: 50px;
    line-height: 50px;
}

#nomecss{
    width: 500px;
}

#mensagemcss textarea{
    width: 500px;
    height: 155px;
    margin: 10px 0px;
    resize: none;
}

#tabelacss{
    display: block;
    background: white;
    height: 243px;
    overflow-x: hidden;
    overflow-y: scroll;
    white-space: wrap;
    border: 1px solid #A9D0F5;
    clear: both;
}

#tabelacss td{
    display: inline;
}

#botao{
    float: right;
    margin-bottom: 10px;
}

JAVASCRIPT

function montarTabela(chat, nome, mensagem, id){
    var html = '';

    chat.push([ [nome] , [mensagem] ]);

    for(i = 0; i < chat.length; i++){
        for(j = 0; j <= i; j++){
            if(i == 0){
                chat[i][2] = gera_cor();
                break;
            }
            else if(chat[i][0] == chat[j][0]){
                chat[i][2] = chat[j][2];
                break;
            }
            else{
                chat[i][2] = gera_cor();
                break;
            }
        }

        html += "<tr>"+
                "<td style=color:" + chat[i][2] + ";><strong>" + chat[i][0] + "</strong></td>"+
                "<td><em> diz:  </em></td>"+
                "<td>" + chat[i][1] + "</td>"+
                "</tr>";
    }    

    document.getElementById(id).innerHTML = html;
}



function gera_cor(){
    var hexadecimais = '0123456789ABCDEF';
    var cor = '#';

    for (var i = 0; i < 6; i++ ) {
        cor += hexadecimais[Math.floor(Math.random() * 16)];
    }
    return cor;
}




document.addEventListener("DOMContentLoaded", function(){
    chat = [];

    document.getElementById("btEnviar").addEventListener("click", function(){

        var nome = document.getElementById("nome").value;
        var mensagem = document.getElementById("mensagem").value;

        //if (nome != "" && mensagem != "") {

            montarTabela(chat, nome, mensagem, "tabela");

            document.getElementById("mensagem").value = "";

        //}
        //else{
            //alert("Preencher todos os campos!");
        //}

    })

})

1 answer

2


The problem is that you are generating new colors for those that already exist in the first loop for (where you have the variable i) of function montarTabela(). With this, each time you assemble the table, new colors will be generated, overwriting the existing ones.

My suggestion is to push the array already with the color set. Just make a loop before the loop that mounts the table and check if there is already a name equal to the one that was typed, and if it exists, take the color value in the array and insert it into the new array item (see explanations in the code):

function montarTabela(chat, nome, mensagem, id){
    var html = '';

    for(var j = 0; j < chat.length; j++){
       // verifica se o nome é igual ao da array
       if(nome == chat[j][0][0]) break;
    }

    // se já existe um nome igual, pega o mesmo valor da cor,
    // em chat[j][2]; se não, gera uma nova cor.
    // Se !chat.length (array vazia) ou
    // se o valor de "j" for igual ao tamanho da array,
    // significa que nada foi encontrado, então chama gera_cor()
    var cor = !chat.length || j == chat.length ? gera_cor() : chat[j][2];
   
    chat.push([ [nome] , [mensagem], cor ]);

    for(var i = 0; i < chat.length; i++){

        html += "<tr>"+
                "<td style=color:" + chat[i][2] + ";><strong>" + chat[i][0] + "</strong></td>"+
                "<td><em> diz:  </em></td>"+
                "<td>" + chat[i][1] + "</td>"+
                "</tr>";
    }    

    document.getElementById(id).innerHTML = html;
    
}



function gera_cor(){
    var hexadecimais = '0123456789ABCDEF';
    var cor = '#';

    for (var i = 0; i < 6; i++ ) {
        cor += hexadecimais[Math.floor(Math.random() * 16)];
    }
    return cor;
}




document.addEventListener("DOMContentLoaded", function(){
    chat = [];

    document.getElementById("btEnviar").addEventListener("click", function(){

        var nome = document.getElementById("nome").value;
        var mensagem = document.getElementById("mensagem").value;

        //if (nome != "" && mensagem != "") {

            montarTabela(chat, nome, mensagem, "tabela");

            document.getElementById("mensagem").value = "";

        //}
        //else{
            //alert("Preencher todos os campos!");
        //}

    })

})
#principal{
    margin: 10px 120px;
    padding: 10px;
    width: 520px;
    background: #086A87;
    border: 1px solid #A9D0F5;
}

#cabecalho{
    width: 500px;
    text-align: center;
}

#chat{
    color: white;
    height: 50px;
    line-height: 50px;
}

#nomecss{
    width: 500px;
}

#mensagemcss textarea{
    width: 500px;
    height: 155px;
    margin: 10px 0px;
    resize: none;
}

#tabelacss{
    display: block;
    background: white;
    height: 243px;
    overflow-x: hidden;
    overflow-y: scroll;
    white-space: wrap;
    border: 1px solid #A9D0F5;
    clear: both;
}

#tabelacss td{
    display: inline;
}

#botao{
    float: right;
    margin-bottom: 10px;
}
<div id="principal">

  <div id="cabecalho">
      <h1 id="chat">CHAT</h1>
  </div>

  <div id="nomecss">
      <input class="form-control" type="text" id="nome" placeholder="Nome">
  </div>

  <div id="mensagemcss">
      <textarea class="form-control" id="mensagem" placeholder="Mensagem"></textarea>
  </div>

  <div id="botao">
      <button id="btEnviar" class="btn btn-danger">Enviar</button>
  </div>

  <div id="tabelacss">
      <table id="tabela"></table>
  </div>

</div>

  • It really helped Sam, thank you very much! Hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.