html javascript open file code example

Example 1: how to open html file with javascript

// In my case, I used a button to activate this function:
function myFunction() {
    window.location.href = 'index.html';
}

Example 2: javascript how to open a file

function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    displayContents(contents);
  };
  reader.readAsText(file);
}

function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.textContent = contents;
}

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);