Reputation: 4290
I want to create Hyperlinks on a page to certain files within its root folder.
So for instance:
\Homepage.html
- This will contain the hyperlinks of:
\1.html
\2.html
\3.html
etc.
I could simply do this manually, but I want to automate the process as the number of files (1,2,3...) will increase.
Can JavaScript do this? If so, how?
Upvotes: 2
Views: 5616
Reputation: 131
A possible work around:
To list under Windows (non Unicode): dir *.exe /B /S /O-G If you want to save the content to a file dir *.exe /B /S /O-G > contentList.txt
Upvotes: 0
Reputation: 19549
I get the impression you're asking about using JavaScript because you may not know how to go about it, at all. If I'm incorrect then my apologies. That said...
As others have stated, JS can't do this alone. You will need a server component (such as PHP) to read the directory to get its files. From that point you have a lot of options. My suggestion is, forget JS altogether unless you have some requirement to use it. Just use DHTML, a basic, fundamental talent of PHP's. Call this file something like main.php
:
<html>
<body>
<?php
// Read directory, spit out links
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<a href="/'.$entry.'">Link to file '.$entry.'</a><br>';
}
}
closedir($handle);
}
?>
</body>
</html>
The above example taken more or less directly from the PHP readdir docs. Based on your example file names, accessing main.php
in your browser this should output something like:
Link to file 1.html
Link to file 2.html
Link to file 3.html
...
You may need to tweak the href
value to reflect the path to the html file, relative to your root folder.
Cheers
Upvotes: 2
Reputation: 983
You'd need to put an HTML element in your page with an ID:
<div id="foo"></div>
Then, with JavaScript,
for (var i = 1 ; i <= 10 ; i++) {
document.getElementById("foo").innerHTML += "<a href=\"" + i + ".html\">Link " + i + "</a>";
}
The escaped quotation marks (\") are important - messing them up can lead to unexpected results.
Edit I read your question carefully and realized you need it to increase as you add more files. In that case, you can either use PHP to generate the JavaScript on the page, i.e.
for (var i = 1 ; i <= <?php echo $maxFileIndex; ?> ; i++) {
document.getElementById("foo").innerHTML += "<a href=\"" + i + ".html\">Link " + i + "</a>";
}
or you could do an AJAX request to the server and populate the div
based on the response.
Upvotes: -1
Reputation: 445
JavaScript works on client-side, in your browser, what you need is a server-side script such as PHP for example.
JavaScript can't do this!
Upvotes: -1
Reputation: 21845
JavaScript cannot do this. You could set up a PHP (or other serverside script) that returns a JSON of the folder contents, since serverside languaged DO have access to that, and then call that script using AJAX.
Upvotes: 1