corn on the cob
corn on the cob

Reputation: 2282

document.createElement flashes up with what I want. Then it disappears

I'm having a small issue with my code. I want the user's input to appear on the screen, like a chatbot. However, it is not doing this. What it's doing instead is flashing up with what I want. Then it is disappearing. Just the message, not the entire thing, but that sometimes happens as well. What has happened and how can I fix it?

function executeNewMessage() {
  var messagecontainer = document.getElementById("message");
  var message = messagecontainer.value;
  var newmessagediv = document.createElement("DIV");
  newmessagediv.innerHTML = message;
  document.getElementById("bodymessages").appendChild(newmessagediv);
}
<div id="site">
  <div id="head">
    Chatbot
  </div>
  <div id="body">
    <div id="bodymessages"></div>
    <span id="bottom"></span>
  </div>
  <div id="foot">
    <form>
      <label for="message">Type your message here</label>
      <input id="message" type="text" />
      <a href="#bottom">
        <button id="submit" onclick="executeNewMessage()">&rarr;</button>
      </a>
    </form>
  </div>
</div>

Upvotes: 0

Views: 445

Answers (1)

Zain Abedin
Zain Abedin

Reputation: 159

The reason that this is happening is because you are using HTML form. The default behavior for form is that they try to submit to the server. That's why you only see the change for a short duration and the page reloads again. Hence, you need to use preventDefault() method.

So, your function should look like this:

function executeNewMessage(e) { //Here e is the event object
  var messagecontainer = document.getElementById("message");
  var message = messagecontainer.value;
  var newmessagediv = document.createElement("DIV");
  newmessagediv.innerHTML = message;
  document.getElementById("bodymessages").appendChild(newmessagediv);
  e.preventDefault();

}

So, what the preventDefault() does is that it prevents the default action of an event.

https://www.w3schools.com/jsref/event_preventdefault.asp

Upvotes: 3

Related Questions