KingAlfredChameleon
KingAlfredChameleon

Reputation: 407

Creating javascript variable for dynamic element

I have a div which contains message updates sent by users. How can I assign a javascript variable to this div so that it's value is always the current content of the div which is consistently updating with messages?

var x = document.getElementById("MessageBox"); // only equals value at the 
// time rather than present value

Upvotes: 0

Views: 72

Answers (2)

royhowie
royhowie

Reputation: 11171

The easiest way to accomplish this would be to assign an .onchange event handler to the element, then assign the node's value to a variable held outside the scope of the function:

var myMSGvalue;
document.getElementById("MessageBox").onchange = function () {
    myMSGvalue = this.value;
    // this will work for <input>, not <div>
}

If you really need to assign your data to an html element, you should use an <input type="hidden">.

However, it would be much better to assign the data to a variable before you append it to the page. For example, let's say you have a web socket:

var messages = [];
socket.on("msg", function (msg) {
    messages.push(msg);
    // msg: { content: "Hello!", author: "notSure" };
    functionToAppendToPage(msg);
})

Now, you can see all the messages received in messages and messages[messages.length - 1] will return the last message received (provided at least one message has been received).

Upvotes: 4

Rupak Das
Rupak Das

Reputation: 71

If your message box field getting data using any Api or through Ajax. You can update the variable before assigning value to message box.

Upvotes: 3

Related Questions