Jesse
Jesse

Reputation: 2599

<input type="file"> change event firing again when navigating back to the page

I have a very basic file uploader. I upload a file, which triggers the change event (console.log). I navigate to a different page, then press the back button. The change event triggers again (the event is logged again to the console).

I am using Chrome. It doesn't happen with text inputs; only file. Anyone know why?

<input type="file" />

<script>
    const input = document.querySelector("input[type=file]");
    input.addEventListener("change", console.log, { once: true });
</script>

Upvotes: 2

Views: 1131

Answers (1)

Dan Knights
Dan Knights

Reputation: 8368

Using Chromium (Brave) the file seems to be cached. So, when you go back, the file is loaded back into the input, triggering the change event.

One workaround would be to set the inputs value to an empty string on page-load:

<input type="file" />

<script>
    const input = document.querySelector('input[type=file]');

    window.addEventListener('load', () => (input.value = ''));
    input.addEventListener('change', console.log);
</script>

Upvotes: 1

Related Questions