You can overwrite the method of the addChildtarget element or , which you can use MutationOvserverto observe the DOM.
considering HTML:
<div id="messages-out" class="messages" style="height: 7em; overflow: scroll">
<div>Anonymous: Hello</div>
<div>John: Hi</div>
</div>
<input id="txtMessage" type="text" autofocus>
rewritten method method:
document.addEventListener('DOMContentLoaded', function(ev)
{
var msgs = document.getElementById('messages-out');
msgs.appendChild = function(childNode)
{
Element.prototype.appendChild.call(msgs, childNode);
msgs.scrollTop = msgs.scrollHeight;
}
document.getElementById('txtMessage').addEventListener('keypress', function(ev)
{
if(13 === ev.which)
{
var div = document.createElement('div');
div.innerHTML = '<em>nick: </em>' + ev.target.value;
msgs.appendChild(div);
ev.target.value = '';
}
});
})
MutationObserver approach:
document.addEventListener('DOMContentLoaded', function(ev) {
var
msgs = document.getElementById('messages-out'),
observer = new MutationObserver(function (mutations)
{
var added = false;
mutations.forEach(function (mutation) {
if ('childList' === mutation.type && 0 < mutation.addedNodes.length)
added = true;
});
if (added)
msgs.scrollTop = msgs.scrollHeight;
})
;
observer.observe(msgs, {childList: true});
document.getElementById('txtMessage').addEventListener('keypress', function(ev)
{
if(13 === ev.which)
{
var div = document.createElement('div');
div.innerHTML = '<em>nick: </em>' + ev.target.value;
msgs.appendChild(div);
ev.target.value = '';
}
});
});
Note. He is not sure if the method is element.appendChildused to add a message, for example. child can be added to the string Element.prototype.appendChild.call(msgs, childNode);or insertBefore. So the second approach is more about catching everything.
source
share