How can I change <p> tag data dynamically after some defined time delay using javascript?

Aishwarya Shiva picture Aishwarya Shiva · Feb 18, 2012 · Viewed 24.7k times · Source

I want to change only <p> tag contents using javascript after a defined time delay. For example a

<p>messages</p>

should change depending on the no. of new messages came. As

<p>messages(1)</p>
<p>messages(2)</p>

Answer

Linus Thiel picture Linus Thiel · Feb 18, 2012

Write your <p> as:

<p class="messages">messages</p>

Your javascript:

function updateMessages() {
    var ps = document.getElementsByClassName("messages");
    for(var i = 0, len = ps.length; i < len; i++) {
        ps[i].innerHTML = "messages (" + messageCount + ")";
    }
}

setTimeout(updateMessages, 1000);

Where 1000 is the number of milliseconds to delay.

Or if you want to do it periodically every 15 seconds, you can use setInterval:

setInterval(updateMessages, 15000);

UPDATE:

I see your comment above:

new messages are retrieved from the database using a JSP function that checks database for new messages

In that case, I gather you want to retrieve that periodically, in effect polling that URL? If you already use a javascript framework, I suggest you look at their AJAX documentation.