Alex Rivera | Logout

Refreshing only one <div> in page with just regular Javascript

Asked 2011-05-13T05:57:59.087
11

If I am not grabbing any information from the server but I want to reload/refresh a div every N seconds how do I do this?

New to javascript: I've tried something like

 <script type = 'text/javascript'>
    function refresh(){
        setTimeout(window.location.reload(), 10000);
    }

    </script>

    <div id='target' onLoad='refresh()'>
<?    
var =grab some rapidly changing content from the web    
print var
  ?>  
    </div>
    <div>
    some stuff that doesn't get refreshed
    </div>

Its not clear to me that I need AJAX if im not getting the new info from the server...so for now i'd like to know how to make it work just in javascript

EDIT: I prefer not to use a library for this basic operation so ideally I wouldn't use jquery, prototype etc. EDIT II: Not sure why people are saying the div isnt changing...the content in it is dynamic it is grabbed (say scraped) from the web...and everytime it goes to grab stuff the stuff has changed at the source...an example could be grabbing search results from twitter which change very rapidly...

Edit
Report

2 Answers

1

You can make a recursive function that will change the content of your div that will look like it is refreshed. Like a timer method, where every set of time will change the time. I don't know how will you get the data that will load on the div, with this I assume you will handle this part.

Here's the function

var gIndex = 1;
function refreshDiv(){
    document.getElementById('target').innerHTML = "Timer " + gIndex++;
    var refresher = setTimeout("refreshDiv()", 1000);
}

<body onLoad="refreshDiv()">
    <div>
        <span>HTML Content</span>
        <div id="target"></div>
    </div>
</body>

You will see that a time is set when setTimeout will call again the refreshDiv() so this will behave like reloading the content of the div. Before the refreshDiv() call again, change the value of you div.

answered 2011-05-13T07:44:28.567
0

If you're keen on doing it yourself to avoid the overhead of including a full library like jquery you can have a look at this.

http://www.dynamic-tools.net/toolbox/ajax/

The simple ajax request demo shows how to retrieve html from a url. You'll want to replace the click trigger with a setInterval to constantly poll instead of triggering on demand.

answered 2011-05-13T07:05:56.637

Your Answer