Javascript spurns the idea of functioning within a head or external file

I'm having success using this code to display a picture preview before uploading. However, I am interested in organizing the script by placing it within an external file or within the html-head section. I am having trouble figuring out how to accomplish this. I believe my issue lies with this particular segment:

reader.onload = (function(theFile) {...

Any help or guidance on this matter would be greatly appreciated :)

Below is the corresponding html code:

<!doctype html>
<html>
<head>

<style>
    .thumb {
            height: 75px;
            border: 1px solid #000;
            margin: 10px 5px 0 0;
    }
</style>

</head>


<body>

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

<script>


    function handleFileSelect(evt) {
            var files = evt.target.files;


            for (var i = 0, f; f = files[i]; i++) {

                if (!f.type.match('image.*')) {
                    continue;
                }

                var reader = new FileReader();

                document.getElementById('list').innerHTML = "";


                //The issue may lie with the ".onload" functionality?
                reader.onload = (function(theFile) {

                    return function(e) {

                        var span = document.createElement('span');

                        span.innerHTML = ['<img class="thumb" src="', e.target.result,
                                   '" title="', escape(theFile.name), '"/><input type="text" name="', escape(theFile.name), '-title" placeholder="title" /><input type="text" name="', escape(theFile.name), '-description" placeholder="description" />'].join('');

                        document.getElementById('list').insertBefore(span, null);
                    };
                })(f);

            reader.readAsDataURL(f);
            }
    }

    document.getElementById('files').addEventListener('change', handleFileSelect, false);


</script>

</body>

</html>

Answer №1

First Step:

To start, create a fresh file, let's call it "extJsFile.js".

Second Step:

Add the content between the tags of your question's code (I'm skipping the code here for simplicity) and then add a single line between the tags of your HTML file. (Assuming both JS and HTML files are in the same project directory)

Note: Always do your research before posing a question, but feel free to continue with your coding endeavors...

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

Adding subdocument to the array of parent document, with only the Object_ID being included

I'm relatively new to working with mongoose. While I have come across similar questions that address this issue, none quite fit my specific problem or help me understand how it relates. My current task involves pushing a subdocument into an array wit ...

Utilizing the default validation in Bootstrap 4 to ensure proper email format in form submissions

Can anyone assist with validating an email form field using Bootstrap 4 without the need for any additional libraries? I believe it might require a simple JavaScript function at the end of the document to check if the fields match. Any guidance on this mat ...

Utilize the appendTo() function and make a switch to dynamically insert content stored in variables into a specified

I am working on developing a page with a central content div, where users have the ability to choose various options that will introduce different additional content. This added content will then present more opportunities for adding new elements, ultimate ...

Tips for interacting with a custom web component using Selenium WebDriver

As a newcomer to writing selenium tests, I am attempting to create an automated test for a carousel feature on our homepage. The objective is to click on one of the carousel navigation buttons and then confirm that a specific inline style has been applied ...

Creating markers from Mysql database is a simple and efficient process

On my website, I have an array of markers that I use to display locations on a Google map. The array format I currently use is: generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]) ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...

What is the best way to convert rows into columns within an array of values?

Below is the structure of my data: let information = [ { X:[ {title: 'Example1', quantity: 25}, {title: 'Example2', quantity: 35} ], Y:[ {title: 'Sample3', quantity: 45}, {title: 'Sample4 ...

Implement AJAX in order to circumvent fees from Google Maps and display maps exclusively upon user interaction by clicking a designated button

Starting July 16, 2018, the Google Maps API is no longer completely free. After July 16, 2018, in order to continue utilizing the Google Maps Platform APIs, you must activate billing for each of your projects. (https://developers.google.com/maps/documentat ...

Showing PHP array in the JavaScript console

I have a straightforward AJAX script that sends 3 variables to an external PHP script. The external script then adds them into an array and sends the array back. I want to output this array in the JavaScript console to check if the variables are being pass ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

Switch up div content - advertisements at the top or bottom

An issue has arisen where the ads on a website are currently being displayed at the bottom of the source code, but they should actually be visible at the top. Here is the ad placeholder code: <div id="300_250_placeholder"></div> And here is ...

Unable to retrieve JSON data from MySQL due to receiving a null value

Currently, I have tried the code below but am facing issues with retrieving data from MySQL. Here is the output: <script type="text/javascript> var somethings= [null,null,null]; </script> While it does show three posts, I seem to be s ...

The client continues to request the file through the REST API

I have noticed a behavior with an audio file stored on the server that clients can request via a REST API. It seems that every time the audio is played again, a new request is sent to the server for the file. Is there a way to prevent this or cache the dat ...

Tips for incorporating a new column into your JavaScript code

function generateGrid(){ var result = ''; var num1 = document.getElementById('num1').value; var counter = 1; for(var x=1; x<=num1;x++){ for(var y=0 ; y<n ...

Website: Showcase Opentok using a Picture-in-Picture design

Currently, I am utilizing Opentok.js and my objective is to showcase both the subscriber and publisher within a Picture-in-Picture layout. I require this setup to be responsive and retain its aspect ratio when resizing the window. Additionally, I need gu ...

What is the method for sorting in MongoDB using the objects in the URL query string?

How can I sort a MongoDB collection in a Node.js application based on the query string provided in the URL? The URL looks like this: http://localhost:5000/v1/bid/sort_bid?sort={"_id": -1,"enquiry_no": 1} I am trying to pass an object i ...

Toggle the visibility of a text area in a text editor based on the selected value in a

I currently utilize the NicEdit text-editor from www.nicedit.com on my Text Area, along with the following code to toggle the visibility of the text area after selecting a value from a drop-down. I need some assistance with the following: 1) I would like ...

What function does the express res.get(field) method serve?

I came across some code snippets demonstrating the use of express res.get(field) Is this method primarily for debugging purposes or are there other applications? The sample code that caught my eye can be found at this link. Here is a snippet of it: var e ...

Learn the process of updating an Xero invoice seamlessly with the xero-Node integration

After successfully integrating Xero with my app for accounting and billing purposes, I am now looking to update a previous invoice that was created in the past on Xero. Is there a solution available for this? Any suggestions would be greatly appreciated. ...

Unable to pass parameters using ViewBag in jQuery within a partial view

Currently, I am in the process of building an MVC3 application with razor syntax. My focus right now is on developing the partial class that will be responsible for handling comments. This is a snippet of my code: <script src="../../Scripts/jquery.js" ...