javascript refuses to work in head/external file

53 views Asked by At

I'm using the following code to have a picture preview before upload. The code is working, but i want to store the script in an external file or at least in the html-head. I can't figure out how to do so. I think my problem is with this part, but I'm not sure at all:

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

Help would be appreciated :)

Here comes the html:

<!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 problem might be caused by this ".onload" ?
                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>
1

There are 1 answers

0
Harpreet Sandhu - TheRootCoder On BEST ANSWER

Step 1:

You just need to create a new file e.g. "extJsFile.js".

Step 2:

Put the content in between the tag of your question's code (I won't repeat the same code, for the sake of simplicity) and then write one line in between tag of your html file.(Assumption - you are putting js and html in same directory of your project)

PS: You should at least google before asking a question, anyway carry on with your codes...