Asynchronous JavaScript with async/await

In this course we will learn how to use the ES2017 async and await keywords to write asynchronous code that is more readable and easier to follow than equivalent code based on long promise chains or deeply nested callbacks.

Watch the Course

Programmatically Opening a File Dialog with JavaScript

I want to take a quick look at file uploads using HTML and JavaScript. Nowadays, many websites don't show the raw <input type="file"> element anymore. Take Facebook, for example:

Facebook post form

When you click on the photo button highlighted above, the native file dialog will open:

File selection dialog on Mac OS X

It's not hard to make that functionality work in modern browsers. In essence, it boils down to triggering a click event on a hidden <input type="file"> whenever the photo button is clicked. Here's a tiny, but working HTML example that reproduces that functionality:

        <input type="file" style="display: none" />
        <button>Open File Dialog</button>

        <script src=""></script>
            $("button").on("click", function() {

And indeed, if we try it out, clicking the "Open File Dialog" button opens the file dialog, as we would expect. Let's now try to automatically open the file dialog immediately after the page has loaded:


That doesn't seem to work. How about delaying the call to the trigger method?

    setTimeout(function() {
    }, 1000);

That doesn't seem to work, either. How come that in the first example, the file dialog was opened successfully? The reason that the first example worked is that the click event was triggered within a code block that was the handler of a user-initiated event.

When we clicked the button, the registered handler function was executed, and the browser kept track of the fact that it was the user who initiated that button click event, not some piece of code. Outside of such user-initiated events, file dialogs cannot be opened programmatically.

Similarly, modern browsers generally don't open a new window when the is not called from within the handler of a user-initiated event. Instead, they'll display a warning like this one:

Google Chrome: "Pop-up blocked" warning

Learn Node