I would like to know if there is a way to only update a div
automatically every x
seconds without having to refresh the whole page would it be possible?
I would like to know if there is a way to only update a div
automatically every x
seconds without having to refresh the whole page would it be possible?
There are many frameworks and libraries that can help you manipulate DOM , such as: JQuery, AngularJS, EmberJS, ReactJS, etc. I will not go into detail about them, but basically you can add specific event listeners to elements that you want to manipulate. Here is an example of how to change the text of a div by adding a listener to the click event. As for updating every X time, you can use the setInterval
function, you can see more details about it at documentation . Hope this helps. :)
<div id="myId">Original</div>
<script>
var div = document.getElementById("myId");
// Adicionando ouvinte de clique
div.addEventListener("click", function (event) {
div.innerHTML = "Alterado =)";
});
// Criando um intervalo
var interval = setInterval(function () {
var date = new Date();
div.innerHTML = date.toLocaleTimeString();
if (date.getSeconds() % 5 == 0) {
div.innerHTML = "Intervalo cancelado :)";
clearInterval(interval);
}
}, 1000/* 1s */);
</script>
Refresh a div
automatically every 3 seconds using HTML
and JavaScript
without updating the entire page:
$(function() {
setTime();
function setTime() {
var date = new Date().getTime();
var string = "Timestamp: "+date;
setTimeout(setTime, 3000);
$('#setTime').html(string);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="setTime"></div>
I made a very simple example, you click on the div and it changes.
In a more real case you should call via ajax a backend and this will return the content, I hope I have helped.
<body>
<div id=teste onclick="changeMe()"> meu texto original </div>
<div id="meuReload" style="border: solid 1px">
3
</div>
<script>
function changeMe(){
document.getElementById("teste").innerHTML = "alterei a div";
n=0;
setInterval(function(){
n=n+1;
document.getElementById("meuReload").innerHTML = "alterando a outra div"+n; }, 2000);
}
</script>
</body>
Abs