Implementing an automatic link generation feature for files within a directory using JavaScript

I could really use some assistance with this. I created a YouTube example, which can be viewed in this PLNKR LINK: http://plnkr.co/edit/44EQKSjP3Gl566wczKL6?p=preview

In my folder named embed, I have files titled p9zdCra9gCE and QrMOu4GU3uU, as shown below:

<div class="ytid" data-str="p9zdCra9gCE">video 1</div>
<div class="ytid" data-str="QrMOu4GU3uU">video 2</div>

I am wondering if there is a way to automatically display any new files like p9zdCra9gCE.html or QrMOu4GU3uU.html that are added to the embed folder on the index page. It should appear alongside other video buttons like this:

<div class="ytid" data-str="p9zdCra9gCE">video 1</div>
<div class="ytid" data-str="QrMOu4GU3uU">video 2</div>
<div class="ytid" data-str="AnotherFile">video 3</div>
<div class="ytid" data-str="AnotherFile">video 4</div>
<div class="ytid" data-str="AnotherFile">video 5</div>

Any suggestions on how to achieve this?

Answer №1

<html>
<head>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/u/264659524/Files/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/u/264659524/Files/myjs.js"></script>
<style>
.ytid{float:left;margin-right:5px;border:1px solid black}
.clear{clear:both;}
</style>
</head>

<body>

<div class="listids">
    <div class="ytid" data-str="p9zdCra9gCE">video 1</div>
    <div class="ytid" data-str="QrMOu4GU3uU">video 2</div>
 </div>


 <div class="clear"></div>
<br>

<div class="vidarea">
            <div class="load_vid"></div>
        <iframe class="vid_src" data-src="" scrolling="no" frameborder="0" marginheight="0" marginwidth="0" style="width:640px; height:460px;display:none;" allowfullscreen=""></iframe>
            </div>

<br><br><br><br><br><br><br><br><br><br>

<textarea class="embed" data-content="&lt;iframe scrolling=&quot;no&quot; frameborder=&quot;0&quot; marginheight=&quot;0&quot; marginwidth=&quot;0&quot; allowtransparency=&quot;true&quot; width:640px; height:460px;&quot; allowfullscreen=&quot;&quot; src=&quot;https://www.youtube.com/embed/[ytvidID]&quot;&gt;&lt;/iframe&gt;" onfocus="this.select();" onclick="this.select()">
    &lt;iframe scrolling=&quot;no&quot; frameborder=&quot;0&quot; marginheight=&quot;0&quot; marginwidth=&quot;0&quot; allowtransparency=&quot;true&quot; width:640px; height:460px;&quot; allowfullscreen=&quot;&quot; src=&quot;https://www.youtube.com/embed/[ytvidID]&quot;&gt;&lt;/iframe&gt;

</textarea>

<script>
    $(document).ready(function(e) {
        $(".vid_src").attr("data-src", "https://www.youtube.com/embed/p9zdCra9gCE");
        var t = "1";
        var n = $(".embed").attr("data-content");
        n = n.replace("[ytvidID]", t);
        $(".embed").html(n);
        $(".listids").slideDown();

        bindEventHandlers();


        $(".embed").keyup(function()
        {
            var valuetoinspect = $(this).val();
            if(valuetoinspect.indexOf(".html") != -1)
            {
                var vidvalue = valuetoinspect.split(".html");
                checkAndMergeVideoListing(vidvalue[0]);
            }
        })
    })

    function checkAndMergeVideoListing(video)
    {
        var count = $(".ytid").length;

        if( $(".ytid[data-str=\""+video+"\"]").attr("data-str") == null)
        {
            var $div = $("<div></div>");
            $div.addClass("ytid");
            $div.attr("data-str",video);
            $div.html("video " + (count+1));

            $(".listids").append($div);

            bindEventHandlers();

            $(".ytid[data-str=\""+video+"\"]").click();
        }
    }

    function bindEventHandlers()
    {
        $(".ytid").unbind("click").click(function(e) {
            var t = $(this).attr("data-str");
            var n = "https://www.youtube.com/embed/" + t + "";
            var r = $(".embed").attr("data-content");
            r = r.replace("[ytvidID]", t);
            $(".embed").html(r);
            $(".vid_src").attr("src", n);
            clearInterval(interval);
            document.querySelector(".load_vid").style.display = "none";
            $(".vid_src").show();
            return
        })
    }
</script>

</body>
</html>

For a demo, you can click here. If you input something like p9zdCra9gCE.html in the embed textarea, it will be added to the video tab and play immediately. Please inform me if there are any discrepancies with your requirements. I hope this solution helps!

Answer №2

In order to assist you in navigating this process, I recommend the following steps:
1. Utilize a server-side language such as PHP. It has been noted that accessing the file system on the server is not feasible with JavaScript or jQuery.
2. Consider employing the scandir() method (a feature of PHP) to retrieve the contents of your designated folder. Refer to http://php.net/manual/en/function.scandir.php for more information.
3. The outcome will be an array containing all files and directories within the scanned location. Implement a foreach loop to create the ytid divs accordingly.

If these instructions seem overwhelming, I recommend seeking out tutorials on PHP through platforms like Codecademy or other online resources. Best of luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Toggle the visibility of the identical div

I am facing a challenge with dynamically hiding and showing various div elements on my website. I have managed to achieve this using show/hide, but the issue arises when I need to show/hide some of the same fields repeatedly. The script works fine on the f ...

Would like to conceal an element only if it is currently visible

Currently in the process of developing a website, I have successfully implemented a dropdown menu that is triggered when clicking on an "About Me" link. This reveals additional links such as biography and interests. The issue I am facing now is regarding t ...

Cease execution of the jQuery function after a specific duration of time

Is there a way to modify this script on my website that displays an image from my webcam? Currently, the image refreshes every 5 seconds, but I want it to stop after 30 seconds to avoid using too much bandwidth. Any suggestions on how I can achieve this? ...

Variations between <div/> and <div></div>

When using Ajax to load two divs, I discovered an interesting difference in the way they are written. If I write them like this: <div id="informCandidacyId"/> <div id="idDivFiles"/> Although both divs are being loaded, only one view is added ...

The CSS styling for the <body> element is not rendering the expected results

website <!DOCTYPE html> <html> <head> <title>Time Tracker</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link ...

`How can I customize the appearance of individual selected <v-list-item> across various sub-groups?`

As a newcomer to Vuetify and Vue in general, I am struggling to solve a specific issue. I need to create multiple sub-groups where only one option can be selected within each "parent" list. Consider an array of cats: options:["Crookshanks", "Garfield", " ...

Steps for ordering by a JSON attribute:

Within my JSON file, I have the following simple structure: {"Item1": {"p1": {"p1sub1": 8, "p1sub2": 7}, "p2": {"p2sub1": 6, "p2sub2": 5} }, "Item2": {"p1": {"p1sub1": 4, "p1sub2": 3}, "p2": {"p2sub1": 2, "p2sub2": 1} } } To retrieve this data, I use th ...

Problem: Repeated attempts to open the popup are unsuccessful

Developed a leaflet map featuring markers that open popups when clicked. Also integrated a search bar for marker searchability. However, encountering an issue where each popup can only be opened once and on selecting a marker name, the zoom functionality w ...

Transforming ASP.NET MVC IEnumerable view model into a JSON array of elements

My goal is to develop a dynamic calendar in ASP.NET MVC that pulls event data from a database to populate it. Right now, the calendar is set up to read a json array of objects, but I am facing an issue with converting my ViewModel data into a format that t ...

Transform the string into a file format, followed by encoding it into base64

Is there a way to take the string const content="<div>How do I <b>convert </b> this string to file?</div>"; and convert it into an HTML file, then ultimately encode it as a base64 string? The method Buffer.from(content).toString(&ap ...

How can we pass a function to a child component in Vue 2.0?

I am facing a challenge with passing a function link to the child component in Vue. Although it is functioning correctly, the code appears in HTML format. How can I enhance this? In my Vue instance, I have: app = new Vue({ ... some code data: { ...

Using JQuery to make POST requests is successful, however, utilizing the XMLHttpRequest object to make

Currently, I am attempting to make a POST request from Javascript to my server in PHP but without utilizing jQuery. The following code successfully sends the required data to the database: var msg = {}; msg['name'] = 'joe'; msg['m ...

A possible invocation of a function using a JavaScript "class"

Presented here is a node module I've been working on: var _ = require('lodash'); function Config(configType, configDir) { this.configType = configType; this.configDir = configDir; }; Config.prototype.read = function() { // read file t ...

Having some trouble with node.js and the fs module when checking if a file exists. Let

I'm a bit confused about the various methods in Node.js to check if a file exists using fs(). One option is to use fs.readFile(): fs.readFile('somefile.html', function (err, data) { if (err) { /* file doesn't exist */ } else { /* ...

Is there a way for me to store the retrieved information from an API into a global variable using Node.js?

function request2API(option){ const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2 const request = new XMLHttpRequest(); request.open('GET', urlStart + ChList[option].videosList + keyPrefix + key); request. ...

How can we improve the Promise.all syntax for cleaner code?

Recently diving into Node.JS, I find the syntax of Promise.all returning an array to be quite frustrating. For example: const requiredData = await Promise.all([ getFirst(city), getSecond(hubIds), getThird(city, customerCategoryKey ...

Create compelling visual representations by utilizing Google charts to draw customized charts based on variable

I have been attempting to create a chart using Google Charts by passing some parameters to the function. I am trying to use these parameters to populate the data, but it doesn't seem to be working as expected. Is it possible to include parameters in t ...

Calculate the date and time three months before or after a specified date

I have the following start date : 2023-09-03T00:00:00+05:30 and end date : 2023-09-10T00:00:00+05:30 My objective is to deduct 90 days from the start date and add 90 days to the end date Afterwards, I need to convert it to UTC format In order to achieve ...

What is the method for combining two box geometries together?

I am looking to connect two Box Geometries together (shown in the image below) so that they can be dragged and rotated as one object. The code provided is for a drag-rotatable boxgeometry (var geometry1). What additional code do I need to include to join t ...

Ways to access a function variable within an AJAX `done` function

This is the JavaScript function I am working with: $('.editable').change(function () { event.preventDefault(); var el_text = this.lastElementChild; var action = this.action; var method = this.method; var data = $(this).serialize(); ...