...

Refreshing a JavaScript function

andyb-uk
09-01-2007, 12:02 PM
Hi,
I'm using the following code to grab certain database contents via PHP and display them in a JavaScript fader (as can be seen at www.offthechartradio.co.uk/scripts/fader.php). At the moment, when the script detects that it has reached the end of the last fading message, it reloads the page to grab the latest available data and cycle through the fading sequence again. To allow the refreshing without reloading our whole website, this script is held in an iframe. However, when the reload occurs in this script, the iframe takes focus in the web browser, which causes some problems for other applications on the site, and also looks a little ugly in the fact that the refreshing status can be seen in the browser window. In various other areas of the site, AJAX is used to get around the window focus problem, however here when I try to do this, although I can get the script to refresh, the fade() function does not start up again. I thought this would then be a simple case of starting up the fade() function after AJAX had finished doing its thing, but I then received an error about texts[text] having no properties.

My understanding on this subject is all self taught and cobbled together, so I may be doing something very stupid, but in essence the question is why doesn't the javascript fader start working again once its data (in var texts) is refreshed.

<?php header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past ?><!-- start: WarpGear JavaScript Fader v1.0 -->

<script language="JavaScript">

<!--

var texts = new Array(

"<font color='{COLOR}' size='1' face='Tahoma'><b>ON AIR:</b> <?php include('http://www.offthechartradio.co.uk/schedule/schedule.php?day=Now&data=Description'); ?></font>",

"<font color='{COLOR}' size='1' face='Tahoma'><b>INTERACT:</b> Get in contact, send us a message or post a topic on the forum using the links below!</font>",<? include('http://www.offthechartradio.co.uk/nowplaying.php'); ?><? include('http://www.offthechartradio.co.uk/nowplaying/getshout.php'); ?>

"<font color='{COLOR}' size='1' face='Tahoma'><b>UP NEXT:</b> <?php include('http://www.offthechartradio.co.uk/upnext.php'); ?></font>");



var bgcolor = "#1B495A"; // background color, must be valid browser hex color (not color names)

var fcolor = "#FFFFFF"; // foreground or font color

var steps = 20; // number of steps to fade

var show = 5000; // milliseconds to display message

var sleep = 30; // milliseconds to pause inbetween messages

var loop = true; // true = continue to display messages, false = stop at last message

// -->

/******************************************************************



WarpGear JavaScript Fader v1.0

Copyright © 2001 WarpGear Software



web: http://www.warpgear.com

email: jsfader@warpgear.com (suggestions & bugreports)

author: Tom Kalmijn



These scripts, referred to as 'the program', are freeware! The

program may be used freely by any individual or organization for

both non-commercial and commercial purposes.



You are encouraged to distribute the program to your friends and

colleagues but only *in its unaltered form*.



The distributable package consists of a zip archive with these

two files: fader.js (this file) and demo.html



Note:

To configure Fader you typically need not alter this file.

See demo.html for configuration instructions.



******************************************************************/



var colors = new Array(steps);

getFadeColors(bgcolor,fcolor,colors);

var color = 0;

var text = 0;

var step = 1;



// fade: magic fader function

function fade()

{





// insert fader color into message

var text_out = texts[text].replace("{COLOR}", colors[color]); // texts should be defined in user script, e.g.: var texts = new Array("<font color='{COLOR}' sized='+3' face='Arial'>howdy</font>");



// actually write message to document

htmlWrite(text_out, "fader");



// select next fader color

color += step;



// completely faded in?

if (color >= colors.length-1)

{

step = -1; // traverse colors array backward to fade out



// stop at last message if loop=false

if (!loop && text >= texts.length-1) return; // loop should be defined in user script, e.g.: var loop=true;

}



// completely faded out?

if (color == 0)

{

step = 1; // traverse colors array forward to fade in again



// select next message

text += 1;

if (text == texts.length) window.location.reload();

if (text == texts.length) return; // loop back to first message



}



// subtle timing logic...

setTimeout("fade()", (color == colors.length-2 && step == -1) ? show : ((color == 1 && step == 1) ? sleep : 50)); // sleep and show should be defined in user script, e.g.: var sleep=30; var show=500;

}



// helper function to make fader cross browser compatible

function htmlWrite(html,id)

{

var obj;

if (document.getElementById) // IE 5+ & Netscape 6+

{

obj = document.getElementById(id);

obj.innerHTML = html;

}

else if (document.all) // IE 4+

{

obj = document.all[id];

obj.innerHTML = html;

}

else if (document.layers) // Netscape 4+

{

obj = document.layers[id];

obj.document.open();

obj.document.write(html);

obj.document.close();

}

}



// getFadeColors: fills Colors (predefined Array)

// with color hex strings fading from ColorA to ColorB

// note: Colors.length equals the number of steps to fade

function getFadeColors(ColorA, ColorB, Colors)

{

len = Colors.length;



// strip '#' signs if present

if (ColorA.charAt(0)=='#') ColorA = ColorA.substring(1);

if (ColorB.charAt(0)=='#') ColorB = ColorB.substring(1);



// substract rgb compents from hex string

var r = HexToInt(ColorA.substring(0,2));

var g = HexToInt(ColorA.substring(2,4));

var b = HexToInt(ColorA.substring(4,6));

var r2 = HexToInt(ColorB.substring(0,2));

var g2 = HexToInt(ColorB.substring(2,4));

var b2 = HexToInt(ColorB.substring(4,6));



// calculate size of step for each color component

var rStep = Math.round((r2 - r) / len);

var gStep = Math.round((g2 - g) / len);

var bStep = Math.round((b2 - b) / len);



// fill Colors array with fader colors

for (i = 0; i < len-1; i++)

{

Colors[i] = "#" + IntToHex(r) + IntToHex(g) + IntToHex(b);

r += rStep;

g += gStep;

b += bStep;

}

Colors[len-1] = "#" + ColorB; // make sure we finish exactly at ColorB

}



// IntToHex: converts integers between 0-255 into a two digit hex string.

function IntToHex(n)

{

var result = n.toString(16);

if (result.length==1) result = "0"+result;

return result;

}



// HexToInt: converts two digit hex strings into integer.

function HexToInt(hex)

{

return parseInt(hex, 16);

}



</script>

<body onLoad="fade()" bgcolor="#1B495A" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><div id="fader" style="position:relative; left:0; top:0; width:602; height:12; text-align:center; background-color:#1B495A;"> </div></body>

andyb-uk
09-04-2007, 05:53 PM
Thought of another possible way around this after some googling. I'm now trying to include the array that changes at the start of the fade() function so that each time it runs it will grab new data. I now have two files, one with the main script, and a second with the data (this is a PHP file not a .js as it needs to execute includes).

I put two alerts into the faderdata file to check it was including properly, and both alerts are displayed when viewing the full page, yet I receive an error saying that texts is not defined, and the page background colour never changes from white, as it should do from the code in the HTML body tag at the bottom of the page.

faderdata.php
alert('Including...');
var texts = new Array(

"<font color='{COLOR}' size='1' face='Tahoma'><b>ON AIR:</b> <?php include('http://www.offthechartradio.co.uk/schedule/schedule.php?day=Now&data=Description'); ?></font>",

"<font color='{COLOR}' size='1' face='Tahoma'><b>INTERACT:</b> Get in contact, send us a message or post a topic on the forum using the links below!</font>",<? include('http://www.offthechartradio.co.uk/nowplaying.php'); ?><? include('http://www.offthechartradio.co.uk/nowplaying/getshout.php'); ?>

"<font color='{COLOR}' size='1' face='Tahoma'><b>UP NEXT:</b> <?php include('http://www.offthechartradio.co.uk/upnext.php'); ?></font>");
alert('Included!');

Main Page
<?php header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past ?><!-- start: WarpGear JavaScript Fader v1.0 -->

<script language="JavaScript">

<!--







var bgcolor = "#1B495A"; // background color, must be valid browser hex color (not color names)

var fcolor = "#FFFFFF"; // foreground or font color

var steps = 20; // number of steps to fade

var show = 5000; // milliseconds to display message

var sleep = 30; // milliseconds to pause inbetween messages

var loop = true; // true = continue to display messages, false = stop at last message

// -->

/******************************************************************



WarpGear JavaScript Fader v1.0

Copyright © 2001 WarpGear Software



web: http://www.warpgear.com

email: jsfader@warpgear.com (suggestions & bugreports)

author: Tom Kalmijn



These scripts, referred to as 'the program', are freeware! The

program may be used freely by any individual or organization for

both non-commercial and commercial purposes.



You are encouraged to distribute the program to your friends and

colleagues but only *in its unaltered form*.



The distributable package consists of a zip archive with these

two files: fader.js (this file) and demo.html



Note:

To configure Fader you typically need not alter this file.

See demo.html for configuration instructions.



******************************************************************/



var colors = new Array(steps);

getFadeColors(bgcolor,fcolor,colors);

var color = 0;

var text = 0;

var step = 1;



// fade: magic fader function

function fade()

{


document.write('<' + 'script');
document.write(' language="javascript"');
document.write(' type="text/javascript"');
document.write(' src="faderdata.php">');
document.write('</' + 'script' + '>');








// insert fader color into message

var text_out = texts[text].replace("{COLOR}", colors[color]); // texts should be defined in user script, e.g.: var texts = new Array("<font color='{COLOR}' sized='+3' face='Arial'>howdy</font>");



// actually write message to document

htmlWrite(text_out, "fader");



// select next fader color

color += step;



// completely faded in?

if (color >= colors.length-1)

{

step = -1; // traverse colors array backward to fade out



// stop at last message if loop=false

if (!loop && text >= texts.length-1) return; // loop should be defined in user script, e.g.: var loop=true;

}



// completely faded out?

if (color == 0)

{

step = 1; // traverse colors array forward to fade in again



// select next message

text += 1;

if (text == texts.length) text = 0;

if (text == texts.length) return; // loop back to first message



}



// subtle timing logic...

setTimeout("fade()", (color == colors.length-2 && step == -1) ? show : ((color == 1 && step == 1) ? sleep : 50)); // sleep and show should be defined in user script, e.g.: var sleep=30; var show=500;

}



// helper function to make fader cross browser compatible

function htmlWrite(html,id)

{

var obj;

if (document.getElementById) // IE 5+ & Netscape 6+

{

obj = document.getElementById(id);

obj.innerHTML = html;

}

else if (document.all) // IE 4+

{

obj = document.all[id];

obj.innerHTML = html;

}

else if (document.layers) // Netscape 4+

{

obj = document.layers[id];

obj.document.open();

obj.document.write(html);

obj.document.close();

}

}



// getFadeColors: fills Colors (predefined Array)

// with color hex strings fading from ColorA to ColorB

// note: Colors.length equals the number of steps to fade

function getFadeColors(ColorA, ColorB, Colors)

{

len = Colors.length;



// strip '#' signs if present

if (ColorA.charAt(0)=='#') ColorA = ColorA.substring(1);

if (ColorB.charAt(0)=='#') ColorB = ColorB.substring(1);



// substract rgb compents from hex string

var r = HexToInt(ColorA.substring(0,2));

var g = HexToInt(ColorA.substring(2,4));

var b = HexToInt(ColorA.substring(4,6));

var r2 = HexToInt(ColorB.substring(0,2));

var g2 = HexToInt(ColorB.substring(2,4));

var b2 = HexToInt(ColorB.substring(4,6));



// calculate size of step for each color component

var rStep = Math.round((r2 - r) / len);

var gStep = Math.round((g2 - g) / len);

var bStep = Math.round((b2 - b) / len);



// fill Colors array with fader colors

for (i = 0; i < len-1; i++)

{

Colors[i] = "#" + IntToHex(r) + IntToHex(g) + IntToHex(b);

r += rStep;

g += gStep;

b += bStep;

}

Colors[len-1] = "#" + ColorB; // make sure we finish exactly at ColorB

}



// IntToHex: converts integers between 0-255 into a two digit hex string.

function IntToHex(n)

{

var result = n.toString(16);

if (result.length==1) result = "0"+result;

return result;

}



// HexToInt: converts two digit hex strings into integer.

function HexToInt(hex)

{

return parseInt(hex, 16);

}



</script>

<body bgcolor="#1B495A" onLoad="fade()" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><div id="fader" style="position:relative; left:0; top:0; width:602; height:12; text-align:center; background-color:#1B495A;"> </div></body>

rwedge
09-06-2007, 10:15 AM
If you have your PHP file output your three lines with a return at the end of each line like
<font color='{COLOR}' size='1' face='Tahoma'><b>ON AIR:</b> <?php include('http://www.offthechartradio.co.uk/schedule/schedule.php?day=Now&data=Description'); ?></font>
<font color='{COLOR}' size='1' face='Tahoma'><b>INTERACT:</b> Get in contact, send us a message or post a topic on the forum using the links below!</font>",<? include('http://www.offthechartradio.co.uk/nowplaying.php'); ?><? include('http://www.offthechartradio.co.uk/nowplaying/getshout.php'); ?>
<font color='{COLOR}' size='1' face='Tahoma'><b>UP NEXT:</b> <?php include('http://www.offthechartradio.co.uk/upnext.php'); ?></font>

and create the texts array out of the AJAX response for the fade script it may work.

example:

global variable additions and fade function changes.var texts, timer;
var bgcolor = "#1B495A"; // background color, must be valid browser hex color (not color names)
var fcolor = "#FFFFFF"; // foreground or font color
var steps = 20; // number of steps to fade
var show = 5000; // milliseconds to display message
var sleep = 30; // milliseconds to pause inbetween messages
var loop = true; // true = continue to display messages, false = stop at last message

var colors = new Array(steps);
getFadeColors(bgcolor,fcolor,colors);
var color = 0;
var text = 0;
var step = 1;

// fade: magic fader function
function fade()
{
// insert fader color into message
var text_out = texts[text].replace("{COLOR}", colors);
// texts should be defined in user script,
// e.g.: var texts = new Array("<font color='{COLOR}' sized='+3' face='Arial'>howdy</font>");
// actually write message to document
htmlWrite(text_out, "fader");
// select next fader color
color += step;
// completely faded in?
if (color >= colors.length-1)
{
step = -1; // traverse colors array backward to fade out
// stop at last message if loop=false
if (!loop && text >= texts.length-1) return;
// loop should be defined in user script, e.g.: var loop=true;
}
// completely faded out?
if (color == 0)
{
step = 1; // traverse colors array forward to fade in again
// select next message
text += 1;
[COLOR="Red"]if (text == texts.length) {
clearTimeout(timer);
yourajaxFunction();
return false;
}
// if (text == texts.length) return;
// loop back to first message
}
// subtle timing logic...
timer = setTimeout("fade()", (color == colors.length-2 && step == -1) ? show : ((color == 1 && step == 1) ? sleep : 50));
// sleep and show should be defined in user script,
// e.g.: var sleep=30; var show=500;
}and then in your ajax response build the texts array and call fade() if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
text = 0;
texts = [];
var dat = xmlHttp.responseText.split('\n');
for (var i = 0;i < dat.length - 1;i++) {
texts.push(dat[i]);
}
fade();

} else {
alert(xmlHttp.status + ' -- ' + xmlHttp.statusText);
}
}
The fade script and AJAX would be included in your main page and the response could be sent to a division rather than the iframe



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum