skip to Main Content

So I’m having a problem where my code doesn’t want to break line even after I put the correct syntax

oldchat = ''

var paragraph = document.getElementById("chat");

function SendMsg() {
  let x = document.getElementById("Username")
  let username = x.value
  let message = prompt();
  chat = (oldchat + "n" + username + ": " + message)
  oldchat = chat;
  let Modifiedmessage = document.createTextNode("n" + username + ":" + message)
  paragraph.appendChild(Modifiedmessage);
}
<input id="Username">
<button onclick="SetUser()">Set Username</button>
<button onclick="SendMsg()">send message</button>
<br>
<div id="chat">

</div>

I was expecting my code to break line have it be like

VibingCat: Hi
User123: Hello there!

4

Answers


  1. n is not a line break in HTML, but <br> Is.

    chat = (oldchat + "<br>" + username + ": " + message)
    paragraph.innerHTML = chat;
    

    Also you don’t need to create a new text node for the modified message in the SendMsg() function, as you are already adding HTML to the paragraph element.

    EDIT: As @Roko C. Buljan innerHTML will make you vulnerable to XSS attacks so don’t use it.
    I’m keeping the answer in case someone had the same idea.

    Login or Signup to reply.
  2. You need to use html tags instead of "n" when you are rendering chat inside the div element, therefore you need to send DOM elements to be rendered inside that div element.

    oldchat + "n" + username + ": " + message
    

    should be

    oldchat + "<br>" + username + ": " + message
    
    Login or Signup to reply.
  3. Hi This is new version of the code

    let oldchat = '';
    const paragraph = document.getElementById("chat");
    const usernameInput = document.getElementById("Username");
    
    function SetUser() {
      const username = usernameInput.value;
      oldchat = '';
      paragraph.textContent = '';
      alert(`Username set to: ${username}`);
    }
    
    function SendMsg() {
      const username = usernameInput.value;
      const message = prompt();
      const chat = oldchat + "n" + username + ": " + message;
      oldchat = chat;
      const modifiedMessage = document.createTextNode("n" + username + ": " + message);
      paragraph.appendChild(modifiedMessage);
    }
    <input id="Username">
    <button onclick="SetUser()">Set Username</button>
    <button onclick="SendMsg()">send message</button>
    <br>
    <div id="chat">
    
    </div>
    Login or Signup to reply.
    • you just need to use a bit of CSS like: line-break: pre-wrap; in order to interpret the n
    • to prevent XSS, use always textContent instead of innerHTML, or create text nodes instead of HTML.
    // DOM utility functions
    const el = (sel, par) => (par || document).querySelector(sel);
    const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
    
    // CHAT:
    
    // Load old messages from DB?
    const messages = [
      {username: "John", message: "Hi Anne!nwhat's up?"},
      {username: "Anne", message: "Hey John!🌞nHow's going with JS?"},
    ];
    
    const elUsername = el("#username");
    const elMessage = el("#message");
    const elSend = el("#send");
    const elChat = el("#chat");
    
    const printMessage = (msg) => {
      const elMsg = elNew("div", {
        className: "msg",
      });
      const elMsgUsername = elNew("div", {
        className: "msg-username",
        textContent: msg.username,
      });
      const elMsgText = elNew("div", {
        className: "msg-message",
        textContent: msg.message
      });
      elMsg.append(elMsgUsername, elMsgText);
      elChat.append(elMsg);
    };
    
    const sendMessage = () => {
      const username = elUsername.value.trim();
      const message = elMessage.value.trim();
      if (!username || !message) return;
      printMessage({username, message});
      elMessage.value = "";
    };
    
    elSend.addEventListener("click", sendMessage);
    
    // Init: Print old messages:
    messages.forEach(printMessage);
    * { margin: 0; box-sizing: border-box; }
    
    #chat {
      padding: 0.5rem;
      font: 1rem/1.3 sans-serif;
    }
    
    .msg {
      padding: 0.5rem 1rem;
      margin: 0.5rem;
      border: 1px solid #aaa;
      background: #eee;
      border-radius: 0.5rem;
    }
    
    .msg-username {
      color: #888;
      font-weight: bold;
    }
    
    .msg-message {
      white-space: pre-wrap; /* NOTICE THIS! */
    }
    
    #message {
      display: block;
      min-width: 20rem;
      min-height: 3rem;
    }
    <div id="chat"></div>
    <input id="username" type="text" placeholder="Username..."><br>
    <textarea id="message" placeholder="Type a message..."></textarea>
    <button id="send" type="button">Send</button>

    As you see from the above:

    1. use const where needed
    2. avoid the use of prompt() use <textarea> instead
    3. avoid the use of HTML inline on* handlers, use addEventListener() instead. JS is supposed to be in one place, and that’s the respective file or tag
    4. don’t name your functions with sentence-case. It’s not a Class
    5. don’t use a string to store your chat messages use a better data format like an Array and object to hold the username, time and message
    6. trim() your messages from whitespaces
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search