Error while fetching elements of an IFrame inside HTA - javascript

We are trying to acheive automation of an Intranet site. We are using HTA along with java script for this purpose. Instead of opening the site in browser, we are using an Iframe, withing the HTA itself, for it (Since the browser security settings bars us from doing anything). Eare able to login to the website,however, after every step from then we get this error message, saying "Unable to get property 'children' of undefined or null reference."
below this it also gives a URL : http://*******..*:8888/cs/domainname/cache/PT_HNAV_JS_MIN_1.js
To be more specific, it is a peoplesoft site. Can someone shed light on how to resolve this ?
Below is the HTML code :
<html>
<head>
<HTA:APPLICATION
APPLICATIONNAME="HTA"
SYSMENU="YES"
>
<meta http-equiv="x-ua-compatible" content="ie=9">
<title>HTA</title>
<script type="text/javascript">
function Start() {
var iframePage = document.getElementById('iframeid').contentDocument;
var userId = iframePage.getElementById("userid");
var passwd = iframePage.getElementById("pwd");
var form = iframePage.getElementById("login");
userId.value='##';
passwd.value='##';
form.submit();
}
</script>
</head>
<body>
<form class="form" name="form">
<input class="links" type="button" value="Project Plan" onclick="Start();" />
</form>
<iframe application="no" src="http://****.**.****:8888/psp/sitename/?cmd=login&languageCd=ENG&" width="600" height="600" id="iframeid">
</body>
</html>
I could find the first occurance of children in the relevant js file is below :
this.fakeBCReqWC = false;
var bchidden = 0;
if(eBC.childNodes.length == 0) bchidden=1;
this.bcScrollUl = ptUtil.id(pthNav.bcScrollId);
if (eBC.children[1])
var clickedURL = eBC.children[1].firstChild.href;
var nChildren = 0;
if (this.bcScrollUl)
nChildren = this.bcScrollUl.children.length;
var nIdx = 0;
if (this.fakeBCSetN) {
var isBCpath = false;
var fakechildindex = 0;
var i = 0;
while(nIdx < nChildren) {
var child = this.bcScrollUl.children[nIdx];
if(child.id && child.id.indexOf ("FAKE") != -1 && child.firstChild && child.firstChild.href == clickedURL) {
isBCpath = true; fakechildindex = nIdx; break; }
nIdx++; }

Changing x-ua-compatible to point to IE 11 resolved the issue. Earlier it pointed to IE9.

not sure why you did application="no"
you should do application="yes" to enable the iframe and parent hta window to communicate and allow your hta to work with the iframe dom.
however, that is from my experience with HTAs while working with IE6/7 and that was a long time ago
see more at msdn:
https://msdn.microsoft.com/en-us/library/ms536496(v=vs.85).aspx#Security

Related

Use of localStorage and IndexedDB in New Google Sites <Embed HTML> doesn't work

I'm trying to make use of the New Google Sites for a web page that I've developed, however, I'm having trouble storing local data. Local files work fine in windows and apple safari/chrome. Try it from Google Sites, and no joy! Additionally, in safari, an error is thrown, "IDBFactory.open() called in an invalid security context".
I really would like to host my site via google sites without linking to another server. I specifically need locally persistent data for just a few small items. I can't seem to make cookies work either.
Any suggestions?
I have tried this on a Windows 10 Surface Pro 2017, Apple iPad running 12.2 of Safari, Apple Mac Mini running macOs Mojave 10.14. I use SimpleHTTPServer from Windows 10 command line to share the files as a web server. I also email the files and open directly on the specified systems. Finally, I have created a New Google Sites website at https://sites.google.com/view/gerrymap It's very simple, just an Embed HTML element with the below text copied into the source code edit box. All are welcome to hit that page if they desire. Otherwise, use the short posted file below.
Instructions are in the HTML page itself.
All code works fine from a local instance of the html file. Can enter new values for the lat, long, rad, and key, save them, and read them. I can also refresh the page, then read them without storing first, and there is no problem. This proves that the values aren't just session persistent.
From Google Sites is a different matter. I set up a site that uses the html file in this question. When I enter new values and press the save button, IndexedDB fails, but localStorage succeeds in returning the values saved. If I press the refresh button, however, and then read the values without attempting to store first, IndexedDB again fails, but localStorage also fails in that it doesn't retrieve any values.
I believe I've correctly implemented the code (although some out there may take exception, I'm sure. No pride here, critics are welcome).
I've done a bunch of google searches, particularly about google sites and indexeddb/localstorage, and also posted on the google community help forum. Still no success.
Currently, I have no fallback methods, but need something relatively simple. Can anyone throw a little joy my way? Thanks in advance!
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test Local Storage</title>
<style>
</style>
</head>
<body onload="initializeValues()">
Instructions: <br />
1. Save this sample code in an html file locally and open in a browser.<br />
2. Enter different values into the lat, long, rad, and key edit boxes.<br />
3. Press TrySave to store the values in indexedDB and localStorage.<br />
4. Refresh the webpage from the browser address line<br />
5. Press the individual Try IndexedDB and Try LocalStorage buttons to attempt<br />
6. Try inserting this code into a New Google Site, or access https://sites.google.com/view/gerrymap/home <br />
<br>
<input id="latitude" /> Latitude<br><br>
<input id="longitude" /> Longitude<br><br>
<input id="radius" /> Radius<br><br>
<input id="key" /> Key<br><br>
<button onclick="TryIndexedDB()" title="This tries to load via IndexedDB">Try IndexedDB</button><br><br>
<button onclick="TryLocalStorage()" title="This tries to load via localStorage">Try localStorage</button><br><br>
<button onclick="trySave()" title="This tries to save the data in both methods (IndexedDB, localStorage)">Try Save</button><br><br>
<button onclick="clearAll()" title="Clear the log space at the bottom of this example page">Clear Log</button><br><br>
<div id="hello">
</div>
<script>
"use strict";
function clearAll() {
document.getElementById("hello").innerHTML = "";
}
// tagBeginDefaultsReplace
var navLatitude = 39;
var navLongitude = -76.7;
var navMaxDist = 200;
var navKey = "PleaseAddYourKey";
function initializeValues() {
document.getElementById("latitude").value = navLatitude;
document.getElementById("longitude").value = navLongitude;
document.getElementById("radius").value = navMaxDist;
document.getElementById("key").value = navKey;
}
function trySave() {
navLatitude = document.getElementById("latitude").value;
navLongitude = document.getElementById("longitude").value;
navMaxDist = document.getElementById("radius").value;
navKey = document.getElementById("key").value;
// Save using indexeddb
getLocationDB(true, FinishIndexedDB);
// Save using localStorage
localStorage.setItem('latitude', navLatitude.toString());
localStorage.setItem('longitude', navLongitude.toString());
localStorage.setItem('radius', navMaxDist.toString());
localStorage.setItem('key', navKey.toString());
mylog("Done saving localStorage");
}
function getLocationDB(bSave, callbackf) {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var openDB;
try {
var myitem;
openDB = indexedDB.open("SampleDatabase", 1);
openDB.onupgradeneeded = function () {
var db = openDB.result;
var store = db.createObjectStore("SampleStore", { keyPath: "id" });
var index = store.createIndex("PosIndex", ["pos.latitude", "pos.longitude", "pos.radius", "pos.navkey"]);
};
openDB.onsuccess = function () {
// Start a new transaction var db = openDB.result;
callbackf("Successfully opened openDB");
var db = openDB.result;
var tx = db.transaction("SampleStore", "readwrite");
var store = tx.objectStore("SampleStore");
if (bSave) {
if (navLatitude != undefined && navLongitude != undefined && navMaxDist != undefined)
store.put({ id: 0, pos: { latitude: navLatitude, longitude: navLongitude, radius: navMaxDist, navkey: navKey } });
else
store.put({ id: 0, pos: { latitude: "38", longitude: "-75.7", radius: "100", navkey: "Please Enter Mapbox Key" } });
callbackf("Save indexeddb finished");
}
else {
var getNavLoc = store.get(0);
getNavLoc.onsuccess = function () {
if (getNavLoc != undefined
&& getNavLoc.result != undefined) {
callbackf("Succeeded reading from store. Result=" + JSON.stringify(getNavLoc.result));
navLatitude = parseFloat(getNavLoc.result.pos.latitude);
navLongitude = parseFloat(getNavLoc.result.pos.longitude);
navMaxDist = parseFloat(getNavLoc.result.pos.radius);
navKey = getNavLoc.result.pos.navkey;
}
else {
callbackf("Succeeded reading from store. Result=undefined");
navLatitude = navLongitude = navMaxDist = navKey = "undef";
}
initializeValues();
}
getNavLoc.onerror = function () {
callbackf("An error occurred getting indexeddb");
}
}
}
openDB.onerror = function () {
callbackf("An error occurred opening openDB");
}
}
catch (e) {
callbackf("Caught error in try block of indexeddb: " + e.Message);
}
}
function TryIndexedDB() {
getLocationDB(false, FinishIndexedDB);
}
function TryLocalStorage() {
mylog("localStorage read");
navLatitude = localStorage.getItem('latitude');
mylog("latitude=" + navLatitude);
navLongitude = localStorage.getItem('longitude');
mylog("longitude=" + navLongitude);
navMaxDist = localStorage.getItem('radius');
mylog("radius=" + navMaxDist);
navKey = localStorage.getItem('key');
mylog("key=" + navKey);
if (navLatitude == undefined)
navLatitude = "undef";
if (navLongitude == undefined)
navLongitude = "undef";
if (navMaxDist == undefined)
navMaxDist = "undef";
if (navKey == undefined)
navKey = "undef";
initializeValues();
}
function FinishIndexedDB(nSucceeded) {
mylog(nSucceeded);
}
function mylog(logstr) {
document.getElementById("hello").innerHTML += "<br>" + logstr.toString();
}
</script>
</body>
</html >
The problem is the way Google Sites is serving the iframe content. I'm not sure of the exact details behind the scenes, but it seems to have a randomly generated domain every time the page loads. Since localStorage and IndexedDB are associated with a specific domain, this causes the saved data to be "lost" when the page reloads.
As an example, here is the iframe's data from when I first loaded the page:
And here is the iframe's data after refreshing the page:
As you can see, the domain is completely different after refreshing, which means it has a brand new empty database.

How to open a URL and estimate the word count using JavaScript?

<html>
<head>
<script type="text/javascript">
function open_urls() {
var url1="https://finance.yahoo.com/";
var newpage=window.open(url1);
alert(newpage.document.body.innerText.split(' ').length);
}
</script>
</head>
<body onload="javascript: open_urls()"></body>
</html>
The code above did not work, how to access DOM for a different URL?
I'd like to open an URL and show the word count of that URL.
You can't simply open another window and page and expect to have access to it. The web follows many security policies to prevent operations like this, such as the Same-Origin policy. Long-story short, you can't access URLs that don't fall under the same-origin as the page you're calling from. You couldn't therefore access Yahoo finance in your example (most likely).
If you were calling from the same origin, you could use an API like fetch to get just the text and do a word count there, or you could even load an iframe and query that: myIframe.contentWindow.document.body.innerHTML.
So knowing that you cannot do this from the browser, you could do it from a NodeJS application (perhaps also using fetch):
var fetch = require('node-fetch');
fetch('https://finance.yahoo.com/')
.then(function(res) {
return res.text();
}).then(function(body) {
console.log(body);
// perform word-count here
});
I understand that you were hoping to do this from the browser, but unfortunately you will not be able to do so for origins that you do not control.
You can try this out.
In you index.html (suppose) write this:
<html>
<head>
<title>Index Page</title>
</head>
<script type="text/javascript">
function poponload()
{
testwindow = window.open("new_window.html", "mywindow","location=1,status=1,scrollbars=1,width=600,height=600");
}// here new_window.html is file you want to open or you can write any url there
</script>
<body onload="javascript: poponload()">
<h1>Hello this can Work</h1>
</body>
</html>
And suppose your new_window.html is like this:
<html>
<head>
<script>
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
}
}
return ret;
}
function run_this(){
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;
alert(count);
}
</script>
</head>
<body onload='javascript: run_this()' id="content">
<h1>This is the new window</h1>
</body>
</html>

JavaScript window.open not detecting C# WebBrowser.Document.Window.Name on another browser instance

I have an HTML with a Javascript code that tries to open a named window if not exists, creates a form, and than posts to that existing window, using its target attribute.
I have a C# Form, with 2 webbrowsers controls in it, side by side, and than I open this HTML in browser1, sets the browser2.Document.Window.Name = "janelaoperacao", the target of the HTML form, and try to post the HTML form, and it opens a new IE window, instead of showing the result in browser2 window.
When I set browser1.Document.Window.Name="janelaoperacao", the posted HTML form shows up normaly on the browser1 window;
So, my problem is browser1.Document is not viewing the browser2.Document named window, and is trying to open another IE window instead. Am I missing some directives, so they can expose to each other inside the same form?
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Teste Java Script Window.Open identificada</title>
<script type="text/javascript">
var PostObj = (function () {
var hiddenForm;
var i;
var createHiddenForm = function () {
hiddenForm = document.createElement("form");
hiddenForm["style"].visibility = "hidden";
hiddenForm["method"] = "post";
hiddenForm["target"] = "janelaoperacao";
hiddenForm["action"] = sucesso.html;
hiddenForm["name"] = "hiddenForm";
hiddenForm["id"] = "hiddenForm";
document.body.appendChild(hiddenForm);
};
this.submit = function (urlDestino) {
createHiddenForm();
document.getElementById("hiddenForm").submit();
};
return this;
})();
function abreJanelaIdentificada(){
var f = window.open("", "janelaoperacao", "location=no");
}
</script>
</head>
<body>
<div id="idPaginaRealizaCopia">
<script type="text/javascript">
//<![CDATA[
function fazTudo(){
abreJanelaIdentificada();
PostObj.submit("file:///D:/temp/sucesso.html?teste=2");
}
//]]>
</script>
<form>
<input type="button" name="botao" value="Abrir" onclick="fazTudo();" />
</form>
</div>
</body>
And the WebBrowser code that does not work (it opens a new IE window):
//after creating the form and stuff -> no errors before navigate, nor NullExceptions
browser1.Navigate("file:///D:/temp/teste.html");
browser2.Document.Window.Name = "janelaoperacao";
But, if I replace browser2 for browser1, it show the success message in the browser1 window (browser1.Document.Window.Name = "janelaoperacao")

Javascript not rendering - Blank head

There's something wrong with my script, it doesn't render the JS correctly. I tried to pinpoint the problem but cannot find any typo. If i load the page, the tag is blank, making all css & other JS disabled. But suprisingly the data is loader correctly. If i remove the script, everything went to normal.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
// Create a connection to the file.
var Connect = new XMLHttpRequest();
// Define which file to open and
// send the request.
Connect.open("GET", "Customers.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var TheDocument = Connect.responseXML;
// Place the root node in an element.
var Customers = TheDocument.childNodes[0];
// Retrieve each customer in turn.
$("#middle").ready( function () {
document.write("<ul class='product'>");
for (var i = 0; i < Customers.children.length; i++)
{
var dul = "wawa"+[i];
//document.getElementById(dul).addEventListener('click', storeData, false);
var Customer = Customers.children[i];
// Access each of the data values.
var Pic = Customer.getElementsByTagName("pic");
var Name = Customer.getElementsByTagName("name");
var Age = Customer.getElementsByTagName("tipe");
var sex = Customer.getElementsByTagName("country");
var checked = window.localStorage.getItem("selected"+i);
// Write the data to the page.
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
document.write(Name[0].textContent.toString());
document.write("</a><div class='age'>");
document.write(Age[0].textContent.toString());
document.write("</div><div class='sex'>");
document.write(sex[0].textContent.toString());
document.write("</div><div class='cex'>");
document.write("<input name='checkbox' type='checkbox' id='wawa_"+i+"'");
if (!checked) {
document.write(" onClick='cbChanged(this, "+i+")'");
} else {
document.write("checked onClick='cbChanged(this, "+i+")'");
}
document.write("></div></li>");
}
document.write("</ul>");
});
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
</script>
</head>
<body>
<div class="container">
<div class="content" id="middle">
</div>
<div class="content" id="footer">
</div>
</div>
</body>
</html>
Ok here's the full source.
You don't close the HTML img tag right
Change
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write("'.jpg><a href='display.html?id="+i+"'>");
// ^ this quote
To
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
// ^ should be here
If you open the developer console you can usually see where errors like this take place. It will also output and javascript errors that you come across so it will make that part a whole lot easier. Do you have any errors in your console?
The dev consoles are:
Chrome: It is built it.
Firefox: Firebug
Safari: It's built it
EDIT:
Don't do var functionName = function() {..} unless you know about how hoisting works. This is contributing to you problem so change
cbChanged = function(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
To
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
Without the above changes the function cbChanged is not hoisted. So if you call it before it is reached you will get an error.
There are several other things that stand out to me on this. You might want to spend some more time on your javascript fundamentals. Read up on why document.write is a bad thing. Try removing parts of the script to narrow down what is causing the problem. It would have made this easier to fix if you had made a fiddle.

Having a cycled (interval) pictures on pre-loaded page through a directory

I am currently working for a library that would like to have a webpage designed digital signage. Most of it has been designed with widgets and through a program called Xcite Pro. I was unable to find any widgets that will allow me to do a slideshow from a directory that will cycle through. I do know the foundations to JavaScript and php.
I do not know how to take a directory and have JavaScript run through an entire directory into a array with picture values. I would like to use the setInterval() command but I seem to only know how to search through a directory by php. I did find a explanation on this site that tells me how to use php to search through and then pull all pictures to be shown. If i can get that to all go into an array that could be used with JavaScript on the site that would actually work fine. The link for that explanation is LINK.
Currently I am just using a folder called pics in my main file. So my directory is "pics" nothing to special. I have seen some things being talked about html5 using a new file search function but that sounds more like for finding particular files rather then taking the entire components of a folder into an array.
Edited 12/23/2013 Per PHPGlue Request and help.
So far the code that I have played with are:
Test html (Main Page)
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Basic XHTML Document</title>
</head>
<body>
<p>President Obama is from Hawaii</p>
<p><img id="scroller" alt="" src="pics/test.jpg" width="600" height="400"/></p>
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='pics\imagefun.php'></script>
</body>
</html>
Common js File in main directory with main page
// common.js
//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
function gteIE(version, className){
if(IE >= version){
bod.className = className;
}
}
function E(e){
return doc.getElementById(e);
}
//]]>
Finally I have 2 pictures in a picture folder along with a imagefun php file.
// imagefun.php
<?php
$imgs = implode(array_merge(glob('*.png'), glob('*.jpg')), "', '");
echo "//<![CDATA[
var imgs = ['$imgs'], ni, iA = [];
for(var i in imgs){
ni = new Image; ni.src = imgs[i]; iA[i] = ni;
}
var pre = onload, iN = 0, iL = imgs.length-1, imgElementId = E('scroller');
imgElementId.src = imgs[0];
onload = function(){
if(pre)pre();
imgElementId.src = iA[0];
setInterval(function(){
if(iN >= iL)iN = 0;
imgElementId.src = iA[++iN];
}, 2000);
}
//]]>";
?>
PHPGlue-- Thank you for all the time that you have put into this. Really not trying to be a pain at all and I really do appreciate all of your patience. I have made sure to swap names based on my file structures. Based on what I see for the basic ideas of the code I would think it should work. As I said though when I load to test it, it will only show the picture I defaulted on the load and then never change. One thing that I have noticed is that if you take the code of the image fun php code and run just that, all it returns is an output of //=IL)iN = 0; imgElement.src = iA[++iN]; }, 2000; } //]]> If I am right then that string of output should be similar to the whole thing rather then just a fragment of a line like it is. I do believe if I am understanding the goal of this code we are having it spit out some code into the src location of the picture location?
Ultimately if possible I would like to have a cloud based file location that I could use to have an individual who works here store pictures in that file and then have the website pull all files in that location to be loaded to the page one at a time at an interval of about 15000ms. I would appreciated any comments or recommendations.
I ended up resolving this myself. Thank you for all the help.
This was a multi parter either way.
I created a php cycler code
Note** This code will actually run through all that was needed just in php. Sadly though as I wanted this to show up on a web page that would cycle on a timer I needed to use some javascript coding. This caused me to change parts of what was used. If you want to do the same thing you drop all code after you have created the pics array or you can even keep up to the point of the forwards and backwards array to be passed into javascript.
<?php
// create a variable to hold the directory location
$Dir = "..\Directory\pics";
// Variable to directory
$dirOpen = opendir($Dir);
// Need to start with a main array
$pics = array();
// Need two arrays for going forward and back
$forwards = array();
$backwards = array();
// Need variables for the program
$c = 0;
$d = 0;
$e = 0;
$i = 0;
$f = 0;
// Need to run through all files in folder and store into an array
while ($curFile = readdir($dirOpen))
{
if(strpos($curFile,'.jpg') !== false)
{
$pics[$i] = $curFile;
++$i;
}
}
closedir($dirOpen);
// declare variables to count previous opening of file
$a = count($pics); // number of pics in the folder
$b = count($pics) - 1; // need to account for starting at 0
// run through pics array fowards
while($f < $a)
{
$forwards[$f] = $pics[$f];
++$f;
}
// run through the pics array backwards
while($b > -1)
{
$backwards[$c] = $pics[$b];
--$b;
++$c;
}
// variables for the functions us
// use function for forward pics
/*function forward($array, $a)
{
$d = 0;
if($d == $a)
{
$d = 0;
return "pics/".$array[$d];
++$d;
}
else
{
return "pics/".$array[$d];
++$d;
}
}
function backward($backwards, $b)
{
if ($e == $b) // going to have a conflict with B becuase right now it should be at -1 or 0. need to compare to the value of -1 and have it reset to the max when reached.
{
}
}
*/
/*// Test the output of each array
foreach($pics as $imgs)
echo $imgs . "<br />";
foreach($forwards as $fors)
echo $fors . "<br />";
foreach($backwards as $backs)
echo $backs . "<br />";
*/
// $forwards and $backwards are the arrays to use for pics cycling
?>
To pass onto the java script I had to use the following code on another php page created to work with all html design of the main page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form name="myForm">
<p> </p>
<p> </p>
<p class="auto-style1"><img alt="" src="" id="pics" height="400" width="300"/></p>
<?php include 'imgCycler.php'; ?>
<script type='text/javascript'>
/* <![CDATA [ */
var forwards = <?php echo json_encode($forwards); ?>;
var backwards= <?php echo json_encode($backwards); ?>;
var max = <?php echo $a ?>;
var count = 0;
function changePic()
{
document.myForm.pics.src='pics/' +forwards[count];
//document.myForm.pics2.src='pics/'+backwards[count];
++count;
if (count == max)
{
count = 0;
}
}
var start = setInterval('changePic()',5000);
</script>
</body>
</html>
Again PHPGlue thank you for all the help you offered. Hope this is useful for anyone else that wishes to do something similar. Please let me know if there are any questions on the code.
Let's start by making a common.js file:
// common.js
//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
function gteIE(version, className){
if(IE >= version){
bod.className = className;
}
}
function E(e){
return doc.getElementById(e);
}
//]]>
Now put the script below in the same folder you keep your images in:
// imagefun.php
<?php
$imgs = implode(array_merge(glob('*.png'), glob('*.jpg')), "', '");
echo "//<![CDATA[
var imgs = ['$imgs'];
for(var i in imgs){
new Image().src = imgs[i];
}
var pre = onload, iN = 0, iL = imgs.length-1, imgElement = E('imgElementId');
imgElement.src = imgs[0];
onload = function(){
if(pre)pre();
imgElement.src = imgs[0];
setInterval(function(){
if(iN > iL)iN = 0;
imgElement.src = imgs[iN++];
}, 2000);
}
//]]>";
?>
Change the imgElementId to yours inside E('imgElementId'). E('imgElementId') must refer to an <img id='imgElementId' /> tag.
Now on your HTML page, refer to this JavaScript page as PHP, at the bottom of your body:
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='path/imagefun.php'></script>
</body>
</html>
Also, change src='path/ to your image folder path, and add or subtract the correct , glob('*.jpg')s and the like, to suit your needs.
Notes:
E(id) gets your Element by id. bod.className changes to the <body class='njs'> to <body class='js'>, assuming you have the class attribute njs in your HTML body tag, for CSS without JavaScript (progressive enhancement). gteIE(version, className) is for Internet Explorer versions greater than or equal to a number passed as version, changing that version or greater's body class attribute to the className argument, because IE10+ won't accept HTML IE comments for CSS changes. imgfun.php caches the images into your Browser memory based on globs found in the folder the script resides in. Then, once these images are loaded into your Browser cache, they are cycled through using setInterval.

Categories

Resources