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>

Wednesday 25 April 2018

CSS Grid Layout responsive navigation

It's possible there is a better way of doing this. There are so many ways to do things using CSS Grid Layout. Anyway, here goes.
<!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 navigation</title>
  <style>
    body {
      font-family: sans-serif;
    }

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

    .grid {
      display: grid;
    }

    .single {
      grid-template-columns: auto;
    }

    .five-columns {
      grid-template-columns: auto auto auto auto auto;
    }

    #menu {
      display: none;
    }

    nav {
      display: block;
      width: 100.05%;
    }

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

<body onload="handleresize()">
  <div id="container">
    <header class="grid single">This is a banner</header>
    <a href="#" class="grid single" id="menu" onclick="toggleMenu()">Menu</a>
    <nav class="grid five-columns">
      <a href="#">Home</a>
      <a href="#">About</a>
      <a href="#">Services</a>
      <a href="#">Portfolio</a>
      <a href="#">Contact</a>
    </nav>
    <main class="grid single">
      <p>Quis fabulas ita quorum dolore. Fore ab nostrud ubi quem aut esse nam appellat, arbitror o litteris, quo quamquam iis laboris. Se elit cernantur, veniam tractavissent arbitror culpa singulis.Tempor id laboris. Minim occaecat ita culpa export, arbitror
        ex eram, export ita constias hic sint ex eram admodum et praesentibus in labore ad probant a minim nam id laboris efflorescere, multos incididunt do exercitation do laborum culpa illum nescius enim. Non elit aliqua quis expetendis. Consequat legam
        nulla cernantur malis nam e elit irure aut constias, de magna constias mentitum an senserit ea commodo, eu aliqua esse tempor appellat, senserit multos offendit, quo fugiat est duis, commodo aute irure vidisse nisi.</p>
    </main>
    <footer class="grid single">This is the footer</footer>
  </div>
  <script>
    window.addEventListener("resize", handleresize);

    function handleresize() {
      var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
      var nav = document.getElementsByTagName('nav')[0];
      var menu = document.getElementById('menu');
      if (width < 640) {
        nav.style.display = 'none';
        menu.style.display = 'block';
      } else {
        nav.setAttribute('style', 'visibility:visible');
        menu.style.display = 'none';
      }
    }

    function toggleMenu() {
      var nav = document.getElementsByTagName('nav')[0];
      if (nav.style.display === 'block') {
        nav.style.display = 'none';
      } else {
        nav.style.display = 'block';
      }
    }
  </script>
</body>

</html>

Tuesday 24 April 2018

Live data to your page using EventSource

In the following example I deliver live data to a web page. It's possible to do this quite easily using node.js and socket.io. However most of the websites I create are delivered through a shared server and the providers won't let me install node.js, so here I provide an alternative.
In this instance I use a combination of HTML, JavaScript and PHP. It would also be possible to use jQuery instead of straight JavaScript and PHP with something like python or indeed any other language. I also use a JSON file which could be replaced by any other data source.

Let's begin with data source tester.json
[
{
"name": "Aragorn",
"race": "Human"
},
{
"name": "Gimli",
"race": "Dwarf"
}
]

Now, the HTML file (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Live data connectivity</title>
</head>
<body>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Race</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
<script src="updatetables.js"></script>
<script src="run.js"></script>
</body>
</html>

Basically we need to check if the HTML table has any data inside. if it doesn't we take data from the data source. If the HTML table does contain data, it will be updated with the contents of the data source. To achieve this we'll use a function inside updatetables.js.
function updateTable(jd, id)
{
  var tbody = document.getElementById(id).tBodies[0];
  for (var i = 0; i < jd.length; i++)
  {
    if(tbody.rows[i] == null)
    {
      /* No data in HTML table */
      var row = tbody.insertRow(i);
      var x = row.insertCell(0);
      x.innerHTML = jd[i].name;
      x = row.insertCell(1);
      x.innerHTML = jd[i].race;
    }
    else
    {
      /* Data in HTML table. Needs updating. */
      var row = tbody.rows[i];
      tbody.rows[i].cells[0].innerHTML = jd[i].name;
      tbody.rows[i].cells[1].innerHTML = jd[i].race;
    }
  }
}

Now that we have a means of updating the table, we need to get the data using stream.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$JSON = file_get_contents('tester.json');
echo 'data: '.json_encode($JSON).PHP_EOL.PHP_EOL;
flush();
?>

Finally we can use the JavaScript EventSource object to call stream.php and get our data. Once we have our data, we can pass it to updatetables.js. This is done through run.js
var source = new EventSource('stream.php');
var tableid = 'myTable';
source.onmessage = function(event)
{
  var jsonData = JSON.parse(event.data);
  jsonData = JSON.parse(jsonData);
  updateTable(jsonData, tableid);
};

If you have recreated these files, to test it all works, try changing the values of items in tester.json and see the updates on your page without refresh.