NewFiveFour | Blog | Portfolio


Javascript: Read the content of a local file

Create an input node first and set its accept attribute to filter the available files and its type to file.

Then set an onchange listener. This will be called when the user has selected a file.

This creates a FileReader object. Sets an onloadcallback that will be called when the file is loaded.

Then you call reader.readAsText if your file is a text file. Its argument is the file object in the input element.

Altogther:

var a = document.createElement("input"); 
a.accept=".json";
a.type="file"; 
a.onchange= function(event) {
  var reader = new FileReader();
  reader.onload = function(e){
    console.log(reader.result)
  };
  reader.readAsText(event.target.files[0]);
}
document.body.appendChild(a)
a.click()

You may want to remove the input element after onchange has been called.

javascript

Javascript: Detect keyboard presses, with control.

If you want to detect when control is pressed, or similar, then:

window.addEventListener("keydown", event => {
    // we look for control s, or the code 19 since safari uses that...
    if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
    alert("Ctrl-S pressed");
    // don't do what it normally does
    event.preventDefault();
    // don't continune propagating the event
    return false;
})
javascript

Javascript: Tranverse the DOM tree looking at attributes

You can traverse the DOM tree, looking at every element node and every attribute, like this:

function traverse() {
  do {
      if(main.nodeType == 1) {
      console.log(main.nodeName)
      for(var i = 0; i < main.attributes.length; i++) {
        console.log(main.attributes[i])
      }
    }
    if(main.hasChildNodes()) traverse(main.firstChild)
    }
  while (main = main.nextSibling)
}
javascript

Javascript: Using XMLHTTPRequest

Here’s a utility method to simply make http requests. You use it like this:

http_request("http://your_url.com/service_url", {
  intermediate: x => {
    console.log("intermediate", x)
  },
  before: x => {
    console.log("before", x)
  },
  success: x => {
    console.log("success", x);
  },
  fail: x => {
    console.log("fail", x)
  }
})

You give it a url. The url must have CORs enabled (i.e. google.com won’t work). In the options object next you can set the method and async value for the XMLHttpRequest.

The options object also takes callbacks. They’re given the current state of the XMLHttpRequest object.

  • before is issued just before the request is sent().
  • intermediate is called when the XHR readyState changes and the request hasn’t either failed or succeed.
  • And fail and success are called when you’ve think. A 304 response is a success.

Here’s the code

function http_request(url, opt) {
  var xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && (this.status == 200 || this.status == 304)) {
      if(opt.success) opt.success(this)
    } else if(this.readyState == 4) {
      if(opt.fail) opt.fail(this)
    } else {
      if(opt.intermediate) opt.intermediate(this)
    }
  }
  xhr.open(opt.method || "GET", url, opt.async || true)
  if(opt.before) opt.before(xhr)
  xhr.send()
}
javascript

Mustache.js: Get the index in an array

Let’s fix Mustache.js looping through arrays but not finding the index.

Let’s say we have the array animals = ["dogs", "cats", "wild boars"].

We can map this into an array of value-index objects.

animals.map((e, i) => { return {e: e, i: i} })

Integrate that with mustache.js and you get

return Mustache.render(`
  <ul>
    {{#animals_indexed}}
      <li>{{i}} {{e}}</li>
    {{/animals_indexed}}
  </ul>`, 
  { animals_indexed: _ => animals.map((e,i)=>{ return {e:e,i:i} })
  }
)
javascript mustache

Page 3 of 84
Previous Next