I have been looking around for the simplest way to refresh a particular div on my page, automatically, every x seconds.
So far I've got:
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('time').innerHTML = Date();
}
However the last part where the innerHTML is set to the date function is what I'd like replaced by the content of the "time" ID, and not an actual date print.
I know I could load an iframe, or externa html page, but I would like to simply call upon an existing div on the page instead of having to change the existing content. Is that possible?
Thanks!
Edit: What I mean is I have a a div that looks like this on the page:
Some stuff
I would like to have that div refreshed every x seconds, so yes, you may ignore the Date() part of my example, I simply found that code as is but when I tried to remove the .innerHTML part it just does nothing, I think lol!
Are you looking for something like this?
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
var now = new Date();
document.getElementById('time').innerHTML = now.getHours() + ":" + now.getMinutes() + ":" +now.getSeconds();
}
</script>
NOTE: The OP is actually wanting to reload a script in an ad service already included on the page. The following does not help with this; however, due to the way the question was asked, I'm leaving this answer since I think it could help others looking for the following type of solution. Just be aware this does not demonstrate how to "rerun" already included (presumably global and non-function'd) code.
Say I have the following div I'd like to dynamically refresh:
<div id="refresh">Refreshes...</div>
jQuery offers the $.ajax group of functions that allow you to dynamically request a page and use the response as HTML. For instance:
$(document).ready(function(){
var $refresh = $('#refresh'),
loaded = 1,
data = {
html: $.toJSON({
text: 'some text',
object: {}
}),
delay: 3
};
var refresh = function(){
$.ajax({
url: "/echo/html/",
data: data,
type: "GET",
success: function(response) {
$refresh.html($refresh.html() + '<br/>#' + loaded);
loaded++;
setTimeout(refresh, 3000);
}
});
};
refresh();
});
http://jsfiddle.net/Ah3jS/
Note, I'm using jsFiddle's echo/html/ functionality here as well. The data variable is tuned to working with this for demonstration purposes. In reality, the data sent with the request is either GET or POST variables like you work with normally. Also, I don't use response in success, but that's because it doesn't return anything in jsFiddle's demo mode.
jQuery make's this stuff pretty easy. Really, I'd think about using it instead of most other approaches (requirements notwithstanding).
Related
If I am here asking it is because we are stuck on something that we do not know how to solve. I must admit, we already searched in StackOverflow and search engines about a solution.. but we didn't manage to implement it / solve the problem.
I am trying to create a JavaScript function that:
detects in my html page all the occurrences of an html tag: <alias>
replaces its content with the result of an Ajax call (sending the
content of the tag to the Ajax.php page) + localStorage management
at the end unwraps it from <alias> tag and leaves the content returned from ajax call
the only problem is that in both cases it skips some iterations.
We have made some researches and it seems that the "problem" is that Ajax is asynchronous, so it does not wait for the response before going on with the process. We even saw that "async: false" is not a good solution.
I leave the part of my script that is interested with some brief descriptions
// includes an icon in the page to display the correct change
function multilingual(msg,i) {
// code
}
// function to make an ajax call or a "cache call" if value is in localStorage for a variable
function sendRequest(o) {
console.log(o.variab+': running sendRequest function');
// check if value for that variable is stored and if stored for more than 1 hour
if(window.localStorage && window.localStorage.getItem(o.variab) && window.localStorage.getItem(o.variab+'_exp') > +new Date - 60*60*1000) {
console.log(o.variab+': value from localStorage');
// replace <alias> content with cached value
var cached = window.localStorage.getItem(o.variab);
elements[o.counter].innerHTML = cached;
// including icon for multilingual post
console.log(o.variab+': calling multilingual function');
multilingual(window.localStorage.getItem(o.variab),o.counter);
} else {
console.log(o.variab+': starting ajax call');
// not stored yet or older than a month
console.log('variable='+o.variab+'&api_key='+o.api_key+'&lang='+o.language);
$.ajax({
type: 'POST',
url: my_ajax_url,
data: 'variable='+o.variab+'&api_key='+o.api_key+'&lang='+o.language,
success: function(msg){
// ajax call, storing new value and expiration + replace <alias> inner html with new value
window.localStorage.setItem(o.variab, msg);
var content = window.localStorage.getItem(o.variab);
window.localStorage.setItem(o.variab+'_exp', +new Date);
console.log(o.variab+': replacement from ajax call');
elements[o.counter].innerHTML = content;
// including icon for multilingual post
console.log(o.variab+': calling multilingual function');
multilingual(msg,o.counter);
},
error: function(msg){
console.warn('an error occured during ajax call');
}
});
}
};
// loop for each <alias> element found
//initial settings
var elements = document.body.getElementsByTagName('alias'),
elem_n = elements.length,
counter = 0;
var i = 0;
for(; i < elem_n;i++) {
var flag = 0;
console.info('var i='+i+' - Now working on '+elements[i].innerHTML);
sendRequest({
variab : elements[i].innerHTML,
api_key : settings.api_key,
language : default_lang,
counter : i
});
$(elements[i]).contents().unwrap().parent();
console.log(elements[i].innerHTML+': wrap removed');
}
I hope that some of you may provide me some valid solutions and/or examples, because we are stuck on this problem :(
From our test, when the value is from cache, the 1st/3rd/5th ... values are replaced correctly
when the value is from ajax the 2nd/4th .. values are replaced
Thanks in advance for your help :)
Your elements array is a live NodeList. When you unwrap things in those <alias> tags, the element disappears from the list. So, you're looking at element 0, and you do the ajax call, and then you get rid of the <alias> tag around the contents. At that instant, element[0] becomes what used to be element[1]. However, your loop increments i, so you skip the new element[0].
There's no reason to use .getElementsByTagName() anyway; you're using jQuery, so use it consistently:
var elements = $("alias");
That'll give you a jQuery object that will (mostly) work like an array, so the rest of your code won't have to change much, if at all.
To solve issues like this in the past, I've done something like the code below, you actually send the target along with the function running the AJAX call, and don't use any global variables because those may change as the for loop runs. Try passing in everything you'll use in the parameters of the function, including the target like I've done:
function loadContent(target, info) {
//ajax call
//on success replace target with new data;
}
$('alias').each(function(){
loadContent($(this), info)
});
I'm relatively new to JavaScript, so please bear with me.
I run an instance of the Blackboard Learn LMS. Feel sorry for me later. Blackboard displays different modules to end users to show different pieces of information. The Announcements module contains non-editable code that sends an Ajax request to display all system-wide and course-specific announcements for that particular user:
<div id="Announcements">
<div id="div_1_1"> </div>
<script type="text/javascript">
Event.observe(window, 'load', function () {
new Ajax.Request('/webapps/portal/execute/tabs/tabAction', {
method: 'post',
parameters: 'action=refreshAjaxModule&modId=_1_1&tabId=_2830_1&tab_tab_group_id=_155_1',
onSuccess: function (transport) {
try {
var res = transport.responseXML.getElementsByTagName('contents')[0].firstChild.nodeValue;
$('div_1_1').innerHTML = res.stripScripts();
page.globalEvalScripts(res, true);
} catch (e) {
$('div_1_1')
.innerHTML = 'Module information is temporarily unavailable. Please reload the page. <!--' + e.toString()
.escapeHTML()
.gsub('-', '-') + '-->';
}
},
onFailure: function (transport) {
$('div_1_1').innerHTML = 'Error loading module.';
}
});
});
</script>
</div>
The module brings up a lot of redundant information that I'd like to hide. Since there's no way to edit that particular code, I've been trying to figure out a way to do one of the following:
Modify the module's contents with additional scripting from another source on the page.
Copy the module's contents to a new, editable module, and display that one instead,
Both methods have proven impossible because the script in the Announcements module only runs once the page has loaded entirely, so there's no way to run a script afterward or wait until the process has completed.
Any ideas on how I might be able to modify the contents without editing its code directly?
I ended up using the DOMSubtreeModified event:
<script type="text/javascript">
$j = jQuery.noConflict();p
$j("#div_1_1").on("DOMSubtreeModified", function () {
var div = document.getElementById("div_1_1");
var inner = div.innerHTML;
inner = inner.substring(
inner.indexOf("<!-- Display course/org announcements -->")
);
div.innerHTML = inner;
});
</script>
newbie to coldfusion/jquery/programming general here. So the overview of my problem is this: I have a ticket id that corresponds with a specific row in my database. When I click a button, I would like one of the columns in that row to change values to "In Testing". My issue is that I do not know how to pull that ticket id number into my jquery function, or if this is even possible. My code:
<script src="/TicketFaster/js/jquery-1.11.3.js"></script>
<script src="/TicketFaster/js/scripts.js"></script>
<cfset ticketid="#ticketid#">
<button id="in_testing" type="button">In Testing</button>
my js:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (#ticketid#);
$.ajax({
url: 'ticketcomponent.cfc?method=in_testing',
type: 'POST',
data: {
test: x
}
});
});
});
The big problem is that these pages are being generated dynamically, so each one will have a different ticket id. Therefore, I need to have the ticket id variable be imported rather than just hard coded in to the jquery function. So is this possible? I did not include the query because it works fine when I use it in other places, just getting the data delivered is the tough part. I appreciate any help you can give me :)
Edit: I was requested to post what I'm trying right now.
The original coldfusion is the same so I'm not going to post that again. Here is the js I'm using:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (<cfoutput>#ticketid#</cfoutput>);
alert(x);
});
});
(I also tried without the cfoutput tags)
As you can see, I'm just trying to do a simple alert to check if my variable has been correctly set. Once I get that to work, then the ajax should follow fairly quickly because I have some experience in that.
What is your specific issue?, can you share a jsfiddle?
for dynamic events replace
$("#in_testing").click(function() {});
for
$(document).on('click','#in_testing', function() {});
This value
var x = (#ticketid#);
in jquery is some like that
var x = $('#ticketid').val(); // for value or $('#ticketid') for object
you just have to take account id created dynamically
Is there a way using the code below to instead of refreshing the time refresh a div id that is already there?
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('drawaddrow').innerHTML = ????;
}
</script>
Say I fi were to replace the time id with the the id that I wanted to refresh what would I put after .innerHTML =???
This is the div I need refreshed every second.
<div id="draw" align="center">
<table>
<tr><td style="height:20px;"></td></tr>
</table>
<TABLE style="float:center;border:5px; border-style:outset;border-color:#E80000; width:850px; border-spacing:0; border-collapes:collapse;" table border="1">
<div id="addrow"><script type="text/javascript">
Draw ("")
[Add]</script></div>
</table>
</div>
The [AddItemsHTML] somehow pulls data from a piece of software telling you what is due and what is not, however the script is not pulling the time every second the browser when refreshed just changed the time on the due status column.
Right now i'm using this to refresh the whole page I just need the drawaddrow div id refreshed.
function refreshPage () {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function () {
setTimeout(refreshPage, 1000);
if (window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}
Updated (on 27/07/2013 #08:20 AM IST):
Having gone through your code, the below is my updated answer.
Plainly assigning a value to the DIV (divaddrow) using (.innerHTML) wouldn't work due to the following reasons:
(a) The DIV has some code enclosed within square braces (like [AddItemsHTML]). I am not sure what technology it uses. But judging by its intended use (which is, to populate the table with data) it sure seems to require a communication with the server to fetch data.
(b) The DIV also has a <script> tag with a call to a function (lets call it cntFn). Plainly assigning the value would not work because value setting wouldn't call/execute the function again (like it does on page load).
Assuming point 1.a is wrong, the normal way to handle 1.b would be to first assign the static contents of the div using .innerHTML and then do either (a) write whatever the "cntFn" does into the function that is refreshing the page (lets call it refreshFn) also (or) (b) call the "cntFn" within the "refreshFn". The latter would also cause a problem here because the "cntFn" has a lot of document.write lines which would repaint the entire page (meaning the other contents of the page would be lost on executing the refresh).
Generally using document.write lines is a bad practice because they repaint the page fully. You can find more about this here.
The best alternate in my opinion would be to use AJAX to refresh the contents. The content of your divaddrow div would form the contents of the AJAX file that needs to be called every 'x' seconds. Be careful with the 'x' seconds part. Do not try to refresh the section every second because realistically it would take time for the AJAX request to reach the server and get the response. Set the refresh interval such that the first request would have been processed by the time the next one comes (at-least 90% of the cases). The amount of data (no. of rows) that the AJAX call would be fetching will also be a factor.
Check this out... I used Jquery for the same
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text(
'I am getting refreshed every 3 seconds..! Random Number ==> '
+ randomnumber);
}, 3000);
});
WORKING FIDDLE
I'm not sure that I understand you, but is this want you mean?
function startTime()
{
document.getElementById('time').innerHTML = document.getElementById('target').innerHTML;
}
This is what I use:
<span>This page will refresh in </span><span id="countdown">60</span>seconds…
<script type="text/javascript">
setInterval(
function() {
if (document.getElementById('countdown').innerHTML != 0) {
document.getElementById('countdown').innerHTML--;
} else {
window.location = window.location;
}
}, 1000);</script>
If I've understood your question correctly, you can do something like this:
window.onload = function () {
function startTime () {
document.getElementById('date').innerHTML = new Date();
}
setInterval(startTime, 1000);
}
HTML:
<div id="time">This a div containing time: <span id="date"></span></div>
This is a JavaScript snippet, based on the original post, that counts the number of seconds since the page has loaded, assuming that there's an element with ID "time" and contents that are entirely numeric.
If the time remaining is given in seconds on the page you're working with, then it would be easy to adjust this accordingly. If the time remaining is not given in seconds, I'd need to see what the text in question actually looks like.
window.onload = startInterval;
var firstTime;
var valAtPageLoad;
function startInterval()
{
firstTime = new Date();
valAtPageLoad = parseInt(document.getElementById('time').innerHTML);
setInterval("startTime();",1000);
}
function startTime()
{
var timeDiff = (new Date() - firstTime)/1000;
document.getElementById('time').innerHTML = Math.round(timeDiff + valAtPageLoad);
}
If you want to reload your DIV and not the entire page, you would have to create the contents of that DIV on the server-side, and then use AJAX to load the DIV´s content. The easiest way to do this, is with jQuery:
function startTime() {
$.get('path/to/div/contents.html', function(data) {
$('#drawaddrow').html(data);
});
}
How do I write a JavaScript timer that will automatically redirect my users to a different page when the timer expires?
#Pawka's answer is correct but you shouldn't be passing a string to setTimeout - you should use a function:
function redirectTimer(url, time)
{
return setTimeout(function()
{
location.href = url
}, time);
}
You should use setTimeout(). For example:
var t = setTimeout("alert('5 seconds!')",5000);
Your code should look something like this (where time is miliseconds):
function redirectTimer(url, time) {
var t = setTimeout("window.location = '" + url + "'",time);
}
P.S. I've wrote this code on the fly and didn't test it.
I think, it would be better to use Refresh Meta Tag instead of javascript. Because if javascript is turned off, this solution will stil works.
Ex.:
<http-equiv="refresh" content="5;URL=http://www.yoursite.com">