Tagged: javascript

A loading spinner for XMLHTTPRequest

Take this CSS which will show a loading spinner similar to iPhone’s. It takes up the entire background, and has 0.5 transparency.

#cover {
  background: url("http://www.aveva.com/Images/ajax-loader.gif") no-repeat scroll center center rgba(255, 255, 255, 0.5);
  position: absolute;
  height: 100%;
  width: 100%;

Now place the html below your holding div <div v-show="loading" id="cover"></div>.

The v-show is vuejs saying only show it when the loading variable is true. But you can turn it on and off however you please.

Let’s turn it on and off – via this.loading=true/false – in our XMLHTTPREQUEST.

I have a very simple reactive observe, onNext and onError. But simply we turn it just before we send the request and turn it off when we receive something back.

observe: function(receiver) {
  var xhttp = new XMLHttpRequest()
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) receiver.onNext(xhttp.response)
    else if(this.readyState ==4 && this.status!=200) receiver.onError(xhttp.statusText)
  xhttp.open("GET", "https://whatever", true)
  this.loading = true
onNext: function(pagination) {
  this.loading = false
onError: function(message) {
  this.loading = false
css javascript vuejs

Javascript: Convert a NodeList to an Array

Unless you can use ES6–in which you can just do Array.from(nodelist).forEach()–you have to do this:

var things = document.querySelectorAll(".things");
Array.prototype.slice.call(things, 0).forEach(...

Or, if you’re a fan of line noise:

Array.prototype.slice.call(document.querySelectorAll(".things"), 0).forEach(...

Formatting/Beautify HTML and Javascript from the command line

First, install the js-beautify package from npm.

sudo npm -g install js-beautify

Now make some dodgily formatted HTML with javascript

echo '<html></body></body><script> var i = 0; var j = 1; </script></html>' > dodgy.html

js-beautify takes -f - to find things from the command line, and --type html to say the javascript is embedded in some HTML. Finally we pipe to less for viewing.

cat dodgy.html | js-beautify -f - --type html

The output is:

    var i = 0;
    var j = 1;

You can add -o dodgy.html to replace the original text in dodgy.html.

unix javascript html beautify npm

Page 1 of 1