Wednesday 23 May 2018

The 2018 Web Developer : Getting the latest node modules

Look at the example package.json below, and in particular, the 'devDependencies' section.
{
  "name": "webpack-playlist-update",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
"devDependencies": {
    "babel-core": "*",
    "babel-loader": "*",
    "babel-preset-es2015": "*",
    "css-loader": "*",
    "sass-loader": "*",
    "style-loader": "*",
    "webpack": "*"
  }
}
The asterisks will tell npm to find the latest versions of those modules on the following command:
npm install

The 2018 Web Developer : Installing webpack

webpack is a node module which allows us to package source files into a single bundle to cut down on the number of HTTP requests.
I'm going to assume we have a directory called 'myApp' and an index.html
cd myApp
npm init -y
This will create a package.json file.
Within package.json, add some text to the "description" field to avoid a warning at the next stage.
If you're not going to use git at this stage also within package.json, add the line "private": true,
Again this is to avoid warnings.
Now we're ready to take node modules.
npm install webpack webpack-cli --save-dev
Now we create a file for configuring webpack.
touch webpack.config.js
Now let's create a directory structure for our source.
mkdir src
cd src
mkdir js
mkdir css
cd js
touch output.js
Now let's add some code to output.js and save.
console.log('Hello world!');
Now let's go back to the myApp directory.
cd ../..
Now we can edit the webpack.config.js file.
Add the following content to webpack.config.js and save.
const path = require('path');
module.exports = {
  mode: 'development',
  entry: './src/js/output.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
}
You can see from the code above a number of things:

  • A 'path' constant to be used to establish where to get files from.
  • A module.exports object.
  • The mode in which we're working.
  • 'entry' is the start location that webpack will look to find the things it need to bundle.
  • 'output' is the location of the bundle.

So our HTML file, index.html will look like this:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Webpack</title>
  </head>
  <body>    
    <script src="./dist/bundle.js"></script>
  </body>
</html>
Now it's time to run webpack
From the command line, and in the 'myApp' directory type:
webpack
The result should be a directory called 'dist', which contains a file called bundle.js.
When loading the page, if we look at the console. It should say 'Hello world!'.

Monday 14 May 2018

Get blogspot content using JavaScript fetch

This example pulls in JSON data from a blog hosted on blogspot.com

First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

const fetch = require('node-fetch');
const url = 'http://some-website.blogspot.com/feeds/posts/default/-/blog?alt=json';
var myFetch = fetch(url);

myFetch.then(response => response.json()).then(function(data) {
  showMyData(data);
}).catch(function(err)
{
  console.log('Caught an error ',err);
});

function showMyData(md) {
  md.feed.entry.forEach((e) => {
    var title = (e.title.$t || '');
var url = (e.link || []).pop().href;
    var date = new Date(e.updated.$t || Date.now());
    var lessLines = e.content.$t.substr(0, 800);
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var theMonth = months[date.getMonth()];
    var theYear = date.getFullYear();
  });
}

Friday 11 May 2018

The 2018 Web Developer : JavaScript JSON processing without jQuery

Enter 'fetch'. The JavaScript API which performs HTTP requests.
First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

In this example, I have a simple .json file which contains a set of URLs and their types.

const fetch = require('node-fetch');
const url = 'feeds.json';
var myFetch = fetch(url);

myFetch.then(response=>response.json()).then(function(data) {
    showMyData(data);
  });

function showMyData(md)
{
  md.forEach((value) => {
    console.log(value.URL, value.TYPE);
  });
}

Thursday 10 May 2018

The 2018 Web Developer : Animating without jQuery

There's not much wrong with jQuery other than it's size. Sometimes when you want to keep your website very lean you may wish to rely on pure JavaScript. In this case, I use the excellent animate.css. Even better than that, you can use animate.scss.
To add it to your project, change to your project directory:
cd myApp/git
Then use the following command:
git clone https://github.com/geoffgraham/animate.scss
Here is an example page which, on page load brings in animate.css and runs the function doTheSlide, to animate the contents of the H1 tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Do the slide</title>
<link rel="stylesheet" href="scss/custom.css" />
</head>
<body>
  <h1>Hello world!</h1>
</body>
</html>
Nothing happens until you create your scss file. custom.css is created thus:
cd myApp/scss
node-sass -w custom.scss custom.css
Now let's put some clever stuff in the custom.scss file.
@import "../git/animate.scss/animate.scss";
h1 {
  @include slideInLeft();
}
Refresh the browser and, hey presto! Now we're animating.

The 2018 Web Developer : Adding and using babel

Babel is a JavaScript compiler. It allows you to use modern JavaScript, then compiles it to a file which will work in all browsers.
To install it, use :
npm install -g babel-cli
To run it, change to the directory containing your JavaScript:
cd myApp
Then run a command like this:
npx babel custom.js -w -o script.js
custom.js is the file you are editing ans script.js is your output file. If you are using the -w (watch) parameter as above, the compilation will take place each time you save custom.js.

Thursday 26 April 2018

CSS Grid Layout accordion

This example highlights an important difference required by CSS Grid Layout to function properly. I've put it in red to make it obvious. If this line used the auto width setting, then as the accordion-content items expanded, they would mess up the layout. By using fractions (fr), we force the columns to retain their widths.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>CSS Grid Layout accordion</title>
  <style>
    body {
      font-family: sans-serif;
    }

    #container {
      max-width: 46em;
      margin: 0 auto;
    }

    .grid {
      display: grid;
    }

    .two-columns {
      grid-template-columns: 1fr 1fr;
    }

    .accordion-link {
      width: 100%;
      display: block;
    }

    .accordion-content {
      overflow: hidden;
      display: none;
    }

    @media (max-width: 640px) {
      .grid {
        grid-template-columns: auto;
      }
    }
  </style>
</head>

<body>
  <div id="container">
    <div class="grid two-columns">
      <div id="column1">
        <a href="#" class="accordion-link">Link 1</a>
        <div class="accordion-content">
          Possumus noster ex excepteur firmissimum, voluptate dolore quid non quem e constias in illum doctrina, quid praetermissum offendit eram voluptate.
        </div>

        <a href="#" class="accordion-link">Link 2</a>
        <div class="accordion-content">
          Quibusdam sunt aliqua commodo culpa, quo ne illum culpa minim, noster commodo officia, id te culpa aliquip.
        </div>
      </div>

      <div id="column2">
        <a href="#" class="accordion-link">Link 3</a>
        <div class="accordion-content">
          Ad ipsum eiusmod. Consequat non legam excepteur, ut duis constias. Sint quibusdam ne anim enim.
        </div>

        <a href="#" class="accordion-link">Link 4</a>
        <div class="accordion-content">
          Se appellat an laboris nam nostrud ad eram nescius.Ubi aliqua officia quo eiusmod malis admodum occaecat ne te ingeniis transferrem, quo minim esse qui quibusdam, sed incurreret praetermissum, commodo te senserit ea aute imitarentur laboris quis officia,
          litteris sint expetendis.
        </div>
      </div>
    </div>
  </div>
  <script>
    var acc = document.getElementsByClassName('accordion-link');

    for (var i = 0; i < acc.length; i++) {
      acc[i].addEventListener('click', function() {
        this.classList.toggle('active');
        var accordioncontent = this.nextElementSibling;
        if (accordioncontent.style.display === 'block') {
          accordioncontent.style.display = 'none';
        } else {
          accordioncontent.style.display = 'block';
        }
      });
    }
  </script>
</body>

</html>