Make an array in Javascript with images from a folder - javascript

I want to navigate through images from a folder with JS, and i want to make an array of the files in the folder. I can't figure how to do that...I want to make the array |var images| and get rid of the links that i have manualy put them there.
<html>
<head>
<title>Ranking Page</title>
<script language="Javascript">
var images = [
"http://dummyimage.com/600x400/000/fff&text=two",
"http://dummyimage.com/600x400/000/fff&text=one"
];
var iIndex;
var iLen = images.length;
function fn_keydown(event) {
var img = document.getElementById("wrapper").childNodes[1];
if (event.keyCode === 39) {
iIndex = (iIndex + 1) >= iLen ? 0 : iIndex + 1;
} else if (event.keyCode === 37) {
iIndex = (iIndex - 1) < 0 ? iLen-1 : iIndex - 1;
}
img.setAttribute("src", images[iIndex]);
}
window.onkeydown = fn_keydown;
window.onload = function() {
iIndex = iLen;
var vEvent = {
keyCode : 39
};
fn_keydown(vEvent);
}
</script>
</head>
<body>
<div id="wrapper">
<img />
</div>
</body>
</html>

You can't do this with JavaScript as it does not have access to a computer's file system. That is because JavaScript was designed with security in mind.
You need to use server side languages for this like asp or php.You would be able to access the filesystem then with the correct security permissions and build your javaScript array code on the server. When the page loads up the paths to your images will exist in the web page and then you can do what you want with them in your javaScript.

Related

Difficulty putting a javascript code in a refresh of an html page

I would like to add this random code in an HTML refresh.
Once the refresh is triggered, it generates a random sequence and adds to the testing123 link.
<html>
<body>
<script type="text/javascript">
function generateRandomString(n) {
let randomString = '';
let characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < n; i++) {
randomString += characters.charAt(
Math.floor(Math.random() * characters.length)
);
}
return randomString;
}
</script>
<meta
http-equiv="refresh"
content="1; URL='https://testing1234.serveirc.com/view.php?id="
/>
<script type="text/javascript">
generateRandomString(25);
</script>
</body>
</html>
If you're going to generate the random part of the URL client-side with JavaScript, it would make more sense to perform the redirect with JavaScript than to construct a <meta> tag for it.
<script>
function generateRandomString(n) {
let randomString = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for ( let i = 0; i < n; i++ ) {
randomString += characters[Math.floor(Math.random()*characters.length)];
}
return randomString;
}
setTimeout(() => {
window.location.href = `https://testing1234.serveirc.com/view.php?id=${generateRandomString(25)}`;
}, 1000); // Redirect after 1 second
</script>
Using a meta tag makes more sense if you can construct the random part from server-side code that constructs the HTML (such as with PHP or Handlebars or some scripting template engine).

Returning to start of script - Which way is best?

Started learning PHP/Javascript by altering example code to display a set of pictures from multiple folders and display the content on a page (this is for artwork from designers to be shown on large 4K monitors in rotation). I've taken a few days to get the below to work so far (which works fine), but I've been reading around and I think it's my basic knowledge that is causing me to get stuck at this point. I can't work out how to get the images to display once each (in the jQuery) and then return back to the PHP at the start of the script that enumerates the image folders again. Would the way forward be to create a loop around the whole PHP / JavaScript script? Or define them both as functions and have them included in a main script that executes the loop (forever)?
I think it's more about the fact that I don't understand how the jQuery is looping forever, I can see the I increment, but don't get how it's looping the images, rather than getting the number of images and incrementing until it hits the last image. Any help or explanation or example would be beneficial.
Here's the code:
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="jquery-1.11.2.min.js"></script>
</head>
<html>
<style type="text/css">
body {
overflow:hidden;
}
</style>
<body bgcolor="#000000">
<Div id="holder">
<img src="team_a/blank.jpg" id="slideshow" style="max-height: 100%; max-width: 100%" />
</Div>
</html>
<?php
// Header("content-type: application/x-javascript");
$team_a = array();
$team_1 = array();
$team_2 = array();
$team_3 = array();
foreach (new DirectoryIterator('team_a') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_1[] = "team_a".'/'.$fileInfo->getFilename(); // Get file names of Team_A directory
}
foreach (new DirectoryIterator('team_b') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_2[] = "team_b".'/'.$fileInfo->getFilename(); // Get file names of Team_B directory
}
foreach (new DirectoryIterator('team_c') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_3[] = "team_c".'/'.$fileInfo->getFilename(); // Get file names of Team_C directory
}
$team_a = array_merge_recursive($team_1, $team_2, $team_3); //Merge all the arrays recursively into $team_a
print_r ($team_a); // A quick test of the contents of $team_a
?>
<script = "text/javascript">
var images = <?php echo json_encode($team_a) ?>;
setInterval(forwardImage, 10000);
//This function will find the key for the current Image
function currentImageKey() {
i = jQuery.inArray($('#slideshow').attr('src'), images);
return i;
}
//This function will move the slideshow forward one
function forwardImage() {
currentImageKey();
if (i < images.length - 1) {
changeImage(i + 1);
} else {
changeImage(0);
}
}
//This function will change to image to whatever the variable i passes to it
function changeImage(i) {
$('#slideshow').stop().animate({
opacity: 0,
}, 1000, function() {
$('#slideshow').attr('src', images[i]);
$('#holder img').load(function() {
$('#slideshow').stop().animate({
opacity: 1,
}, 1000)
})
})
}
</script>

how to create a dynamic array in javascript based on the number of files in same directory

I have a static page, which I'm using for viewing pictures, and the javascript does the slide show; however, I would like to dump the pictures in same directory and when page is opened, the javascript will create an array with all the pictures without me having to edit the array for every scenario.... is this possible?... I know javascript has some security restrains when it comes to read from local filesystem. here's the static page and javascript
<!doctype html>
<html lang="en">
<head>
<title>Picture Show</title>
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<script type="text/javascript" src="slideshow.js"></script>
</head>
<body>
<!-- Insert your content here -->
<div id="container">
<div id="header">
<h1>Slide Show</h1>
<a id="link" href="javascript:slideShow()"></a>
</div>
<div id="slideShow">
<img name="image" alt="Slide Show" src="pics/0.jpg" />
</div>
</div>
</body>
</html>
javascript
//javascript code for slideshow
//pictures
var imgs = [ "pics\/0.jpg", "pics\/1.jpg", "pics\/2.jpg", "pics\/3.jpg", "pics\/4.jpg", "pics\/5.jpg" ];
var imgNum = 0;
var imgsLength = imgs.length-1;
var time = 0;
//changing images function
function changeImg(n) {
imgNum += n;
//last position of array
if (imgNum > imgsLength) {
imgNum = 0;
}
//first position of array
if (imgNum < 0) {
imgNum = imgsLength;
}
//console.log(images.tagName);
document.image.src = imgs[imgNum];
return false;
}
//slideshow function
function slideShow() {
var tag = document.getElementById('link').innerHTML;
if(tag == "Stop") {
clearInterval(time); //stoping slideshow
document.getElementById('link').innerHTML = "Start";
document.getElementById('link').style.background = "yellow";
}
else { //all other cases come here
time = setInterval("changeImg(1)", 4000);
document.getElementById('link').innerHTML = "Stop";
document.getElementById('link').style.background = "green";
}
}
window.addEventListener('load', slideShow);
It's not possible to automatically read a directory with in-browser javascript because of security issues. You have two options here:
Make a multiple file input and let the user select the images to display. He could just use "ctrl+a" inside a directory to select everything ... of course this is bad cuz it requires a file select for every slideshow.
or...
Make a server side application that will upload the files or a list with their path. This will do the trick just the way you want, but the application must be installed and running on the machine in order to work. This could be easily achieved with nodejs and I bet you will find a module that will help you.

Using data from .CSV with JavaScript

I have an .csv file that looks like:
oS,browName,browVer,timeCanvas,timeSvg
Windows,Firefox,25.0,0.25,1.23
Windows,Opera,12.16,0.572,1.465
And i would like to do a function that will count arithmetic mean for timeCanvas and timeSvg looking something like:
for (int i = 0; i < maxrow; i++)
{
if(oS=Windows)
{
if(browName=FireFox
{
if(browVer=25.0)
{
a=a+1;
timeC=timeC+timeCanvas
timeS=timeS+timeSvg
}
}
}
...
}
I googled my problem and only solution i could find was jquery-csv 0.7 with toObjects method (http://code.google.com/p/jquery-csv/)> I would like to know is it possible with this libaarry to do what i want?? And if there are some good examples (couldnt find myself)??
..........................................................................
Edit:
so i tryed vadim solution but it deos not working and i dont know hwat i do worng.Here is the code.
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
function draw(){
var a = 0,
timeC = 0,
timeS = 0,
meanCFf=0,
meanSFf= 0;
$.get('test1.csv').done(function(data) {
var i,
lines = data.split('\n'),
line = lines[0].split(','),
oS = line.indexOf('oS'),
browName = line.indexOf('browName'),
browVer = line.indexOf('browVer'),
timeCanvas = line.indexOf('timeCanvas'),
timeSvg = line.indexOf('timeSvg');
for(i=1; i<lines.length; i++) {
line = lines[i].split(',');
if(line[oS] === 'Windows') {
a++;
timeC += parseFloat(line[timeCanvas], 10);
timeS += parseFloat(line[timeSvg], 10);
}
}
});
meanCFf = timeC/a;
meanSFf = timeC/a;
var os1 = document.getElementById("osInfo1");
os1.innerHTML = "Twoja średnia to: " + meanCFf;
var os2 = document.getElementById("osInfo2");
os2.innerHTML = "Twój sytem operacyjny to: " + meanSFf;
}
</script>
</head>
<body onload="draw()">
<p id="osInfo1"></p>
<p id="osInfo2"></p>
</body>
It looks like for loop is not working coz a is zero all the time.
Using jQuery you can do something like this:
JavaScript (script.js)
$(function() {
var a = 0,
timeC = 0,
timeS = 0;
$.get('test1.csv').done(function(data) {
var i,
lines = data.split(/\r\n|\n/),
line = lines[0].split(','),
oS = line.indexOf('oS'),
browName = line.indexOf('browName'),
browVer = line.indexOf('browVer'),
timeCanvas = line.indexOf('timeCanvas'),
timeSvg = line.indexOf('timeSvg');
for(i=1; i<lines.length; i++) {
line = lines[i].split(',');
if(line[oS] === 'Windows' && line[browName] === 'Firefox' && line[browVer] === '25.0') {
a++;
timeC += parseFloat(line[timeCanvas], 10);
timeS += parseFloat(line[timeSvg], 10);
}
}
$('#osInfo1').html("Twoja średnia to: " + timeC/a);
$('#osInfo2').html("Twój sytem operacyjny to: " + timeS/a);
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>CSV Test</h1>
<div id="osInfo1"></div>
<div id="osInfo2"></div>
</body>
</html>
You could get the folder manually with javascript and then attempt to manually parse it OR you could use PHP.
PHP has some great libraries for working with CSV which come standard.
Rather than go through all the effort of working with it manually every time I would personally create a simply PHP JSON service which carries out the function you require of the csv simply and delivers the data. You can then retrieve you the data using Javascript AJAX allowing you perform the code you need as usual.
Overall, I think you'll find this will mean less code for you and theres a lot more documentation on the net to support both the PHP CSV and the JSON service.
Of course, this is assuming that you have a server that has PHP.

updating a parameter within location (src) using JavaScript

How can I parse the value of status = 'logged-out' to the 3 tags below it, updating the value of login_status = 'logged-out'?
<script type="text/javascript">
window.ndm = window.ndm || {};
window.ndm.cam = {'status':'logged-out'};
</script>
<script src="http://foo.com/adserver/ndm/js.php?position=header-ad&section_id=NEWS&login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=middle-ad&section_id=NEWS&login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=footer-ad&section_id=NEWS&login_status=SUBSCRIBER"></script>
Keep in mind, there also heaps of other script tags on the page, so to identify the relevant ones. I got this function.
function getScriptSourceName(name){
var scripts = document.getElementsByTagName('script');
for (i=0;i<scripts.length;i++){
if (scripts[i].src.indexOf(name) > -1)
return scripts[i].src;
}}
Therefore to find the relevant script tags I want, i call the function - getScriptSourceName('foo.com');
How can I then update the login_status parameter's value to use the one declare at the very top?
I think this should work (below the HTML file for testing).
Look at changeStatus method (I triggered it by button click for testing).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript">
window.ndm = window.ndm || {};
window.ndm.cam = {'status':'logged-out'};
</script>
<script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
<script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
<script src="http://foofoo01.com/some.php?login_status=SUBSCRIBER"></script>
<script>
function changeStatus(name)
{
var scripts = document.getElementsByTagName('script');
var scriptsToChange = [];
for (var i = 0; i < scripts.length; i++)
{
if (scripts[i].src.indexOf(name) > -1)
{
var oldSrc = scripts[i].src;
var newSrc = oldSrc.replace(/(login_status=).*/,'$1' + 'logged-out');
scripts[i].setAttribute("src", newSrc);
scriptsToChange.push(scripts[i]);
}
}
for (var k = 0; k < scriptsToChange.length; k++)
{
document.getElementsByTagName("head")[0].appendChild(scriptsToChange[k]);
}
}
</script>
</head>
<body>
<button type="button" onclick="changeStatus('foo.com')">Change status</button>
</body>
</html>

Categories