Building a Multiplayer TicTacToe Game with Meteor

Meteor is a popular, full stack web framework that makes it very easy to prototype your ideas and get from development to production really fast. Its reactive nature and the use of DDP, make it a great candidate for building simple, multiplayer, browser games.

In this tutorial, I’ll show you how to build a multiplayer TicTacToe with Meteor, using its default front-end templating engine, Blaze. I will assume that you have played around with Meteor a bit, and of course, that you feel comfortable coding with JavaScript.

If you have zero experience with Meteor I’d recommend you first follow the TODO app tutorial on the official Meteor site.

You can find the code for the completed app in the accompanying GitHub repo.

Creating the app

If you don’t have Meteor installed you should follow the instructions on their site according to your OS.

Generate the Scaffolding

Now with Meteor installed, open your terminal and run the following command:

meteor create TicTacToe-Tutorial

This will create a folder with the name of your app (in this case TicTacToe-Tutorial). This new folder contains the basic file structure for an app. There’s actually a sample app inside.

Navigate to the folder:

cd TicTacToe-Tutorial

And now run the app:

meteor

I know, I know… that’s a terribly hard-to-remember command, and you’ll be using it a lot, so you should start memorizing it!

If everything went fine now the console should be building the app. After it’s done, open your web browser and go to http://localhost:3000 to see the app running. If you have never done so before, I’d recommend you play around with the sample app. Try to figure out how it works.

Let’s take a look at the file structure. Open your app’s folder. The only things there that we care about (for now) are the client folder and the server folder. The files inside the client folder will be downloaded and executed by the client. The files in the server folder will only be executed on the server and the client has no access to them.

These are the contents in your new folder:

client/main.js        # a JavaScript entry point loaded on the client (we won't be needing this)
client/main.html      # an HTML file that defines view templates
client/main.css       # a CSS file to define your app's styles
server/main.js        # a JavaScript entry point loaded on the server
package.json          # a control file for installing NPM packages
.meteor               # internal Meteor files
.gitignore            # a control file for git

Building the board

A TicTacToe board is a simple three by three table; nothing too fancy, which is great for our first multiplayer game, so we can focus on the functionality.

The board will be downloaded by the client, so we’ll be editing files inside the client folder. let’s begin by deleting the contents on main.html and replacing it with the following:

client/main.html

<head>
  <title>tic-tac-toe</title>
</head>

<body>
  <table id="board">
    <tr>
      <td class="field"></td>
      <td class="field"></td>
      <td class="field"></td>
    </tr>
    <tr>
      <td class="field"></td>
      <td class="field"></td>
      <td class="field"></td>
    </tr>
    <tr>
      <td class="field"></td>
      <td class="field"></td>
      <td class="field"></td>
    </tr>
  </table>
</body>

Don’t forget to save your files after making changes! Otherwise, they won’t be acknowledged by Meteor.

Now let’s add some css to our board. Open the main.css file and add the following content:

client/main.css

table
{
  margin: auto;
  font-family: arial;
}

.field
{
  height: 200px;
  width: 200px;
  background-color: lightgrey;
  overflow: hidden;
}

#ui
{
  text-align: center;
}

#play-btn
{
  width: 100px;
  height: 50px;
  font-size: 25px;
}

.mark
{
  text-align: center;
  font-size: 150px;
  overflow: hidden;
  padding: 0px;
  margin: 0px;
}

.selectableField
{
  text-align: center;
  height: 200px;
  width: 200px;
  padding: 0px;
  margin: 0px;
}

We’ve also added a few extra ids and classes that we’ll be using later on in this tutorial.

Finally, delete client/main.js, as we won’t be needing it, and open the app in the browser to see how it looks.

This is fine and all, but is not an optimal solution. Let’s do some refactoring by introducing Blaze Templates.

Creating a Template

Templates are pieces of HTML code with their own functionality that you can reuse anywhere in your app. This is a great way to break up your apps into reusable components.

Before creating our first template, we’ll add two more folders inside the client folder. We’ll call one html and the other one js.

Inside the html folder, create a new board.html file with the following content:

client/html/board.html

<template name="board">
  <table id="board">
    <tr>
      <td class="field"></td>
      <td class="field"></td>
      <td class="field"></td>
    </tr>
    <tr>
      <td class="field"></td>
      <td class="field"></td>
      <td class="field"></td>
    </tr>
    <tr>
      <td class="field"></td>
      <td class="field"></td>
      <td class="field"></td>
    </tr>
  </table>
</template>

Now, on the main.html folder replace the content inside the body tag with the following code:

client/main.html

<head>
  <title>tic-tac-toe</title>
</head>

<body>
  {{>board}}
</body>

This will insert our template with the property name="board", inside the body tag.

But this is the same hard coded board that we had before. Only now, it’s inside a template, so let’s take advantage of the template helpers to build our board dynamically.

Using helpers

We’ll declare a helper in the board template that will provide us with an array with the same length as the dimensions we want our board to have.

inside the js folder create a file called board.js with the following content:

client/js/board.js

import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';

Template.board.helpers({
  sideLength: () => {
    let side = new Array(3);
    side.fill(0);

    return side;
  }
});

Now, we’ll use this helper in the board’s template HTML to repeat one single row for each element in the array provided by the helper. To help us with this, we’ll use the Each-in Spacebars block helper.

Replace the content inside the board.html file with the following:

client/html/board.html

<template name="board">
  <table id="board">
    {{#each sideLength}}
      {{#let rowIndex=@index}}
      <tr>
        {{#each sideLength}}
        <td class="field" id="{{rowIndex}}{{@index}}">
          {{{isMarked rowIndex @index}}}
        </td>
        {{/each}}
      </tr>
      {{/let}}
    {{/each}}
  </table>
</template>

Notice that we’re looping through the array twice, once for the rows and once for the columns, instantiating the corresponding tag (tr or td) as we go. We’re also setting their id properties as the @index of the row + @index of the column. What we get is a two digits number that will help us identify that element, with its position on the board.

Check out the app at http://localhost:3000 to see how it’s looking so far.

UI

Now that we have a good looking board, we’ll need a play button and a tag to show information on the current game.

Let’s begin by creating the ui.html file inside the html folder… you know the drill. Now, add the following content to it:

client/html/ui.html

<template name ="ui">
  <div id="ui">
    {{#if inGame}}
      <p id="status">
      {{status}}
      </p>
    {{else}}
      <button id="play-btn">Play</button>
    {{/if}}
  </div>
</template>

As you can see we’re using the #if Spacebars block helper and the inGame helper (that we haven’t yet defined) as a condition. There’s the status helper inside the p tag too. We’ll define that later also.

How does it work? #if the inGame helper returns true, the player will see whatever’s in the status helper. Otherwise, we’ll simply show the play button.

Don’t forget, for this component to be displayed we need to add it to our main client template:

client/main.html

<head>
  <title>tic-tac-toe</title>
</head>

<body>
  {{>ui}}
  {{>board}}
</body>

Logging in

We won’t be dealing with any login UI. We will install a very useful package called brettle:accounts-anonymous-auto that will automatically log in all users anonymously into our app.

Head over to your console and run the following command:

meteor add brettle:accounts-anonymous-auto

Now, when you open the app for the first time after adding this package, it’ll create a new user, and every time you open the app on the same browser it’ll remember you. If we’re not keeping any data from said user, it might be better to just remove them when they log out. But we’re not going over that in this tutorial.

Building the Game

Finally, we’re going to start building the game itself! Let’s go over the functionality we’ll be implementing, to have a clear view of what’s coming next.

We’ll need functionality for:

Continue reading %Building a Multiplayer TicTacToe Game with Meteor%


Source: Sitepoint

How to Create Beautiful HTML & CSS Presentations with WebSlides

HTML Presentations with WebSlides

Presentations are one of the best ways to serve information to an audience. The format is short and sharp, made up of small, digestible chunks, which makes any topic under discussion engaging and easier to understand. A presentation can contain all kinds of data, represented by many different elements, such as tables, charts, diagrams, illustrations, images, videos, sounds, maps, lists, etc, all of which lends great flexibility to this medium of expression.

Particularly on the web, presentations come in handy on many occasions, and there are loads of tools at your disposal to create some nifty ones. Today, I’ll introduce you to WebSlides — a small and compact library with a nice set of ready-to-use components, which you can leverage to build well-crafted and attractive web presentations:

WebSlides “is about telling the story, and sharing it in a beautiful way.”

In fact, one of WebSlides’ main benefits is that you can share your story beautifully and in a variety of different ways. With one and the same architecture — 40+ components with semantic classes, and clean and scalable code — you can create portfolios, landings, longforms, interviews, etc.

Besides, you can also extend WebSlides’ functionality by combining it with third-party services and tools such as Unsplash, Animate.css, Animate On Scroll, and so on.

WebSlides is easy to learn and fun to use. Let’s see it in action now.

Getting Started with WebSlides

To get started, first download WebSlides. Then, in the root folder, create a new folder and call it presentation. Inside the newly created presentation folder, create a new file and call it index.html. Now, enter the following code, which contains the needed references to the WebSlides’ files (make sure the filepaths correspond to the folder structure in your setup):

[code language=”html”]
<!doctype html>
<html>
<head>

<!– Google Fonts –>
<link href=”https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,700,700i%7CMaitree:200,300,400,600,700&subset=latin-ext” rel=”stylesheet”/>
<!– CSS Base –>
<link rel=”stylesheet” type=’text/css’ media=’all’ href=”../static/css/base.css”/>
<!– CSS Colors –>
<link rel=”stylesheet” type=’text/css’ media=’all’ href=”../static/css/colors.css”/>
<!– Optional – CSS SVG Icons (Font Awesome) –>
<link rel=”stylesheet” type=’text/css’ media=’all’ href=”../static/css/svg-icons.css”/>

<body>
<!– PUT WEBSLIDES PRESENTATION CONTENT HERE –>

<script src=”../static/js/webslides.js”></script>
<script>
window.ws = new WebSlides();
</script>

<!– OPTIONAL – svg-icons.js (fontastic.me – Font Awesome as svg icons) –>
<script defer src=”../static/js/svg-icons.js”></script>
</body>
[/code]

Now, you’re ready to go.

Create a Web Presentation with WebSlides

In this section you’re going to create a short, but complete presentation, which explains why SVG is the future of web graphics.
Note: If you are interested in SVG, please check my articles: SVG 101: What is SVG? and How to Optimize and Export SVGs in Adobe Illustrator.

You’ll be working step by step on each slide. Let’s get started with the first one.

Continue reading %How to Create Beautiful HTML & CSS Presentations with WebSlides%


Source: Sitepoint

PHPBot – Can a PHP Bot Help You Look up Documentation Faster?

I came across PHPBot the other day (not to be confused with Botman or Fondbot) – a “chatbot” which helps you look up PHP manual entries and generates example code for them.

If you follow me on Twitter, you know I don’t believe in chatbots being chatbots – as someone who’s built some for both commercial purposes and personal ones, and as someone who was around in the age of IRC auto-responding scripts, I see chatbots as a little more than a marketing fad designed to impress today’s Snapchat generation. However, every now and then one will appear that’s actually useful. Could this be the one? Let’s take a look.

Bot welcoming image

Concept

The idea is that you use the text input on the page to enter a PHP related term (like “ksort”) and the application will reply with an explanation and some example code, like so:

<img src=”https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/08/1502792810Screenshot-2017-08-15-12.26.24-1024×473.png” alt=”PHPBot’s reply to ksort input" />

Different queries will produce different responses. So, if you ask it for echo:

<img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/08/1502792917Screenshot-2017-08-15-12.28.06-1024x706.png" alt="PHPBot's reply to echo" />

Continue reading %PHPBot – Can a PHP Bot Help You Look up Documentation Faster?%


Source: Sitepoint

Incredible Design Tools & Resources, August 2017

Keeping up to date with the latest design tools, resources, apps, books and trends is tough, and sieving through the things that are relevant, useful and interesting to us is even tougher. Which is why we’ve started a Product Hunt collection showcasing the absolute best design tools and resources that we’ve discovered, some of which we use here at SitePoint!

Follow the collection on Product Hunt to receive a notification when we (editors Alex Walker, and myself, Daniel Schwarz) add something to the collection that you really, really must check out. Plus, we’ll personally handpick the best of the best to talk about in a monthly article, like we’re doing right now! Welcome to Best Design Products: August Edition!

Rage Grade by FullStory

  • Summary: benchmark your customer frustration

Rage Grade by FullStory uses machine learning to detect negative signals in the customer experience as they use your app or website, and awards the overall experience a grade between -C and A. It also brings the top ten key moments of frustration to your attention, and lets you rewind the session to the exact moment of rage. It’ll detect signals such as error clicks, mouse thrashing and form abandonment, and even benchmark the customer experience against industry competition.

FullStory doesn’t tell you what you want to hear, it tells you the full story (sorry, I had to!).

Link: https://www.producthunt.com/posts/rage-grade-by-fullstory

Figma 2.0

  • Summary: design tool for handoff and prototyping

Figma has been boldly leading the charge in the realtime-multiplayer design collaboration space, allowing multiple designers to work on the same design file at the same time, and it works on macOS, Windows and in the browser.

Version 2.0 makes Figma a triple-threat, as it now offers prototyping and design handoff features alongside the standard design tools we’ve come to love. We even use it at SitePoint! Design handoff can be used in a “view only” mode so that developers don’t accidentally mess up design files, and they don’t need to be a paying team member either. Win win!

Link: https://www.producthunt.com/posts/figma-2-0

Figma design app

Gravity Sketch VR

  • Summary: bring VR into your design workflow

Prepare yourselves, this stuff is…well…there are no words, really. Gravity Sketch is an immersive 3D design tool for creating models, scenes and other 3D objects using virtual reality headgear like the Oculus Rift. Gravity Sketch VR co-founder Daniela Paredes claims that you can totally spend 8 hours sketching 3D objects in the virtual reality world.

You really have to see the video to appreciate its beauty.

Link: https://www.producthunt.com/posts/gravity-sketch-vr

Freehand 2.0 by InVision App

  • Summary: collaborative, freehand sketching and wireframing

InVision App have been adding some really amazing new features to their Craft Sketch Plugin recently (Craft Stock, Craft Prototype, etc), but one that’s really stood out for designers has been Craft Freehand, now on its 2nd version. Freehand works in the core InVision App (as well as in Sketch) and is accessible to collaborators of all types (designers and stakeholders) on a multitude of devices, allowing them to collaborate in realtime on rough digital sketches in a way that’s both fun and easy.

Sketch alongside your high-fidelity mockups, or start from scratch and iterate fresh concepts with your team.

Multiple cursors + unlimited canvas + unlimited creativity = win.

Link: https://www.producthunt.com/posts/freehand-2-0-from-invision

Chain

  • Summary: create dynamic colour relations in Sketch

Inspired by SASS functions, chain allows designers to create dynamic colour relations in Sketch. For example, you could reduce the saturation of [x] amount of layers by 80% all at once, even if all of those layers were a different colour.

Link: https://www.producthunt.com/posts/chain-4

Smartmockups 2.0

  • Summary: create stunning mockups without using Photoshop

Mockups were very trendy at one stage, although really they should have been called product screenshots as “mockup” is already a design term. Traditionally, we used Photoshop to insert our website/app screenshot into a real image of an actual device using Smart Objects, but now that a multitude of design tools are now becoming mainstream, Photoshop is becoming much less trendy as a design tool for user interface design. So…how do we create these mockups now?

Smartmockups. Version 2 delivers us GIF functionality, so we can now create animated mockups using the latest device previews, and there’s also a bunch of new options that allow for better tweaking of the final output (cropping, zooming, etc).

Link: https://www.producthunt.com/posts/smartmockups-app-2-0

Smartmockups design tool

Keys for Sketch

  • Summary: advanced keyboard shortcut manager for Sketch

Not every feature in Sketch has a shortcut. Granted, these are usually less-common features, but it’s still annoying when you have to scurry through the menu bar to find certain things. Plus, not all keyboard shortcuts are intuitive, and some may conflict with Sketch Plugins. Designers coming over from Photoshop may also want to reassign keyboard shortcuts.

Enter Keys For Sketch.

Link: https://www.producthunt.com/posts/keys-for-sketch

Keys For Sketch Plugin

Continue reading %Incredible Design Tools & Resources, August 2017%


Source: Sitepoint

How to Create a QR Code Reader for Your Mobile Website

The barcode and QR code have modernized our shopping and searching experience. Customers carrying smartphones can now pick up a product anywhere in the world, scan its barcode or its QR code using one of the many free phone apps and find out its lowest price as well as where it can be bought.

Screenshots of apps with barcode scanner buttons

Companies like Walmart and Amazon have embraced this technique to draw customers to their online and offline stores using their phone app. Other companies like Fedex and UPS allow customers to scan the codes on packages using a phone app, instead of needing to manually type in long lists of characters.

If the users of your mobile website have a need to type in long codes like activation codes or they like to look up specific products on your website based on a model number printed in a magazine or advertisement, then you too can take advantage of QR codes to eliminate the frustration of tiny keyboards and spare them the need to double check for errors.

QR Code Scanning with your Mobile Website

You don’t need a native phone app to scan QR codes —it’s quite simple to create your own QR code reader. Your website running on a smartphone equipped with a camera and running a little JavaScript can do the same trick.

Here is a demo of a text field with an in-built QR button. In addition to being able to type text into the field, users can also click a button to activate the camera.

Browser Requirements:
Your users need to be on an iPhone running iOS 6 or higher or an Android phone running Android 3.0 or higher. Other devices have not been tested.

See the Pen Bare QR reader demo by SitePoint (@SitePoint) on CodePen.

If you are on a supported device, go ahead and click it. Depending on your phone, it will either launch the camera immediately or ask you whether to open the camera or browse your photo library. On unsupported devices, the browser will open up a regular file explorer window.

If you don’t have a QR code handy to scan, here is one that shows the first 8 digits of Pi.

Test the QR Code Reader: QR code encoding the value of Pi

Creating the QR Code Reader

The magic starts with the file upload element. We spruce it up with an accept attribute which tells the browser that we only want images and we give it a capture attribute which means we want the input to be captured now, as opposed to uploading an old picture from the phone’s memory.

<input type=file
       accept="image/*"
       capture=environment>

Beautifying the Upload element

Because the file upload element is difficult to style and takes up a whole bunch of space, we want to shrink it down to an icon, which we can achieve by making it invisible and wrapping it inside a label element. The label element provides an area for the user to click on, as well as giving us an area to add our QR icon.

Notice that we’ve also added a tabindex=-1 attribute to prevent the user from accidentally reaching the file upload element with the tab key, since we intend to make it invisible.

<label class=qrcode-text-btn>
  <input type=file
         accept="image/*"
         capture=environment
         tabindex=-1>
</label>

The class name of qrcode-text-btn on the outer label element allows us to style both elements with the following CSS:

.qrcode-text-btn {
  display: inline-block;
  height: 1em;
  width: 1em;
  background: url(qr_icon.svg) 50% 50% no-repeat;
  cursor: pointer;
}

.qrcode-text-btn > input[type=file] {
  position: absolute;
  overflow: hidden;
  width: 1px;
  height: 1px;
  opacity: 0;
}

In the first CSS block, we are giving the label element a display:inline-block property, which allows us to assign a height and width to the element.

Then we give it a background image, which is the QR icon that the users of our QR code reader will see.

In the second CSS block we are using a direct descendant selector (>) to select the file upload element and apply a couple of CSS properties to make that element invisible:

We give it a position:absolute property, so that it is excluded from the regular document flow, which means objects around it will flow over and under it as if it didn’t exist.

We give it the width:1px and height:1px properties, so that it doesn’t accidentally cover up other things on the page.

We give it an opacity:0 property, so that it becomes transparent and therefore hidden. Note that we can’t simply use display:none, because some browsers will completely disable the file upload element if we do that.

Introducing the Text Input element

Next we introduce the text input element that will house the QR button for our QR code reader.

<input type=text class=qrcode-text
><label class=qrcode-text-btn>
   <input type=file
         accept="image/*"
         capture=environment
         tabindex=-1>
</label>

Tip:
Any white-space characters, including empty lines, in between 2 inline elements will create a gap that you might not want and affects our math. We have eliminated the white-space above by moving the end bracket (>) to the next line touching the other element’s opening bracket (<).

This is what our QR code reader should look like so far:

Continue reading %How to Create a QR Code Reader for Your Mobile Website%


Source: Sitepoint

Duolingo for PHP – How Much PHP Can Apps like Mimo Teach?

Mimo is an app which claims to teach coding “on the go”. As a long time Duolingo user, I could relate to this approach – particularly as I was becoming increasingly interested in achieving some degree of basic Swift literacy in the coming weeks.

In an attempt to objectively assess the app’s ability to teach people new things, I decided to look at what it’s offering and see if it’s something I can recommend to people just starting out with a new language.

Mimo homepage screenshot at getmimo.com

Model

The application is free for the first one or two lessons of every course, at which point you’re asked to either spread the word on social media, or pay to unlock the next one. The next one after that, however, has to be paid for.

The pay to unlock screen in Mimo

Like Duolingo, Mimo uses streaks to gamify learning, keeping track of how many consecutive days you’ve been using it. To further gamify things, the app features a bunch of badges and achievements to collect, though the real killer feature would be a Duolingo-like “follow user” approach which also allows for direct communication on certain lesson slides.

Achievements in Mimo

Obviously, there’s quite a bit of collecting and achieving to be done in Mimo!

The app lets users set their own desired learning frequency, but all this does is dictate how often the app will remind you to use it – it has no other effects on the app in terms of course length or content.

Reminder frequency menu

It’s a sad world where 20 minutes of learning per day is considered insane, isn’t it?

At the time of writing, Premium access costs a whopping 54.99 GBP per year, or 4.58 GBP per month, but only payable annually. It seems the app’s developers are well aware of the fact that most people abandon learning and self-improvement apps on mobile after a month.

The Upgrade to Premium screen in Mimo

The biggest problem is that with what’s offered for free, it’s hard to justify spending this amount.

Courses

The application offers individual language courses – PHP, HTML, Swift, “Hacking”, etc. but also course tracks that include several courses in order, aimed at teaching a bigger whole. For example, the Make a Website course has the sub courses: Programming, Programming 2, HTML, CSS, JavaScript, etc.

The course track selection screen

Page 1 of the Make a Website track

Page 2 of the Make a Website track

This course doesn’t whet the appetite, however – what’s covered is a very basic and language agnostic concept of variables, and then the paid content begins. That’s 2 out of 43 lessons free – hardly enough content to make an educated purchasing decision. Also, despite what seems like a lot of content (43 lessons), it should be noted that lessons are typically 10-15 minutes long.

Continue reading %Duolingo for PHP – How Much PHP Can Apps like Mimo Teach?%


Source: Sitepoint

How to Get Started With restdb.io and Create a Simple CMS

How to Get Started With restdb.io and Create a Simple CMS

This article was sponsored by restdb.io. Thank you for supporting the partners who make SitePoint possible.

Databases strike fear into the heart of the most experienced developers. Installation, updates, disk space provision, back-ups, efficient indexing, optimized queries, and scaling are problems most could do without. Larger organizations will employ a knowledgeable dev ops person who dedicates their life to the database discords. Yet the system inevitably fails the moment they go on vacation.

A more practical option is to outsource your database and that’s exactly the service restdb.io provides. They manage the tricky data storage shenanigans, leaving you to concentrate on more urgent development tasks.

restdb.io: the Basics

restdb.io is a plug and play cloud NoSQL database. It will be immediately familiar to anyone with MongoDB experience. The primary differences:

  • there’s no need to manage your installation, storage or backups
  • you can define a data structure schema in restdb.io
  • data fields can have relationships with other fields in other collections
  • there’s no need to define indexes
  • data can be queried and updated through a REST API authenticated by HTTP or Auth0/JWT tokens
  • queries and updates are sent and received in JSON format
  • there are tools to enter, view and export data in various formats
  • it supports some interesting bonus features such as codehooks, email, web form generation, websites, realtime messaging, and more.

A free account allows you to assess the service with no obligation. Paid plans offer additional storage space, query throughput, developer accounts and MongoDB integration.

In the following sections I’ll describe how to:

  1. configure a new database and enter data
  2. use that data to render a set web pages hosted on restdb.io, and
  3. use the API to provide a search facility for content editors.

Step 1: Create a New Database

After signing up with a Google, Facebook or email account, you can create a new empty database. This generates a new API endpoint URL at yourdbname.restdb.io:

create a new database

Step 2: Create a New Collection

A database contains one or more collections for storing data. These are analogous to SQL database tables. Collections contain “documents” which are analogous to SQL database records (table rows).

The restdb.io interface offers two modes:

  1. Standard mode shows the available collections and allows you to insert and modify data.
  2. Developer mode allows you to create and configure collections.

enter developer mode

Enter Developer Mode (top-right of screen) and click the Add Collection button.

create a new collection

A collection requires a unique name (I’ve used “content”) and an optional description and icon. Hit Save to return to your database overview. The “content” collection will appear in the list along with several other non-editable system collections.

Alternatively, data can be imported from Excel, CSV or JSON files to create a collection by hitting Import in the standard view.

Step 3: Define Fields

Staying in Developer Mode, click the “content” collection and choose the Fields tab. Click Add Fields to add and configure new fields which classify the data in the collection.

create fields

Each collection document will sore data about a single page in the database-driven website. I’ve added five fields:

  • slug – a text field for the page path URL
  • title – a text field for the page title
  • body – a special markdown text field for the page content
  • image – a special image field which permits any number of uploaded images (which are also stored on the restdb.io system)
  • published – boolean value which must be true for pages to be publicly visible.

Step 4: Add Documents

Documents can be added to a collection in either standard or developer mode (or via the API). Create a few documents with typical page content:

create documents

The slug should be empty for the home page.

Step 5: Create a Database-Driven Website (Optional)

restdb.io provides an interesting feature which can create and host a database-driven website using data documents in a collection.

The site is hosted at www-yourdbname.restdb.io but you can point any domain at the pages. For instructions, click Settings from the Database list or at the bottom of the left-hand panel then click the Webhosting tab.

To create the website, Pages must be configured in Developer Mode which define templates to view the content. Templates contain a code snippet which sets:

  1. the context – a query which locates the correct document in a collection, and
  2. the HTML – a structure which uses handlebars template syntax to insert content into appropriate elements.

Click Add Page to create a page. Name it the special name /:slug – this means the template will apply to any URL other than the home page (which does not have a slug). Hit Save and return to the page list, then click the /:slug entry to edit.

Switch to the Settings tab and ensure text/html is entered as the Content Type and Publish is checked before hitting Update:

create page

Now switch to the Code for “/:slug” tab. Enter the context code at the top of the editor:

{{#context}}
{
  "docs": {
    "collection": "content",
    "query": {
      "slug": "{{pathparams.slug}}",
      "published": true
    }
  }
}
{{/context}}

This defines a query so the template can access a specific document from our content collection. In this case, we’re fetching the published document which matches the slug passed on the URL.

All restdb.io queries return an array of objects. If no document is returned, the docs array will be empty so we can add code to return that the page is not available immediately below the context:

<!doctype html>
{{#unless docs.[0]}}
  <html>
  <body>
    <h1>Page not available</h1>
    <p>Sorry, this page cannot be viewed. Please return later.</p>
  </body>
  </html>
{{/unless}}

Below this, we can code the template which slots the title, body and image fields into appropriate HTML elements:

{{#with docs.[0]}}
  <html>
  <head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <style>
      body {
        font-family: sans-serif;
        font-size: 100%;
        color: #333;
        background-color: #fff;
        max-width: 40em;
        padding: 0 2em;
        margin: 1em auto;
      }
    </style>
  </head>
  <body>
    <header>
      {{#each image}}
        <img src="https://sitepoint-fbbf.restdb.io/media/{{this}}" alt="image" />
      {{/each}}

      <h1>{{title}}</h1>
    </header>
    <main>
      {{markdown body}}

      <p><a href="/">Return to the home page...</a></p>
    </main>
  </body>
  </html>
{{/with}}

Note our markdown body field must be rendered with a markdown handler.

Save the code with Ctrl|Cmd + S or by returning to the Settings tab and hitting Update.

The /:slug page template will apply to all our content collection — except for the home page, because that does not have a slug! To render the home page, create a New Page with the name home with identical settings and content. You may want to tweak the template for home-page-specific content.

Once saved, you can access your site from https://www-yourdbname.restdb.io/. I’ve created a very simple three-page site at https://www-sitepoint-fbbf.restdb.io/.

For more information about restdb.io page hosting, refer to:

Step 6: API Queries

Creating a site to display your data may be useful, but you’ll eventually want to build an application which queries and manipulates information.

restdb.io’s REST API provides endpoints controlled via HTTP:

  • HTTP GET requests retrieve data from a collection
  • HTTP POST requests create new documents in a collection
  • HTTP PUT requests update documents in a collection
  • HTTP PATCH requests update one or more properties in a document in a collection
  • HTTP DELETE requests delete documents from a collection

There are a number of APIs for handling uploaded media files, database meta data and mail but the one you’ll use most often is for collections. The API URL is:

https://yourdbname.restdb.io/rest/collection-name/

The URL for my “content” collection is therefore:

https://sitepoint-fbbf.restdb.io/rest/content/

Queries are passed to this URL as a JSON-encoded querystring parameter named q, e.g. fetch all published articles in the collection:

https://sitepoint-fbbf.restdb.io/rest/content/q={"published": true}

However, this query will fail without an API key passed in the x-apikey HTTP header. A full-access API key is provided by default but it’s advisable to create keys which are limited to specific actions. From the database Settings, API tab:

create a new database

Click Add New to create a new key. The one I created here is limited to GET (query) requests on the content collection only. You should create a similarly restricted key if you will be using client-side JavaScript Ajax code since the string will be visible in the code.

It’s now possible to build a standalone JavaScript query handler (ES5 has been used to ensure cross-browser compatibility without a pre-compile step!):

// restdb.io query handler
var restDB = (function() {

  // configure for your own DB
  var 
    api = 'https://sitepoint-fbbf.restdb.io/rest/',
    APIkey = '597dd2c7a63f5e835a5df8c4';

  // query the database
  function query(url, callback) {

    var timeout, xhr = new XMLHttpRequest();

    // set URL and headers
    xhr.open('GET', api + url);
    xhr.setRequestHeader('x-apikey', APIkey);
    xhr.setRequestHeader('content-type', 'application/json');
    xhr.setRequestHeader('cache-control', 'no-cache');

    // response handler
    xhr.onreadystatechange = function() {
      if (xhr.readyState !== 4) return;
      var err = (xhr.status !== 200), data = null;
      clearTimeout(timeout);
      if (!err) {
        try {
          data = JSON.parse(xhr.response);
        }
        catch(e) {
          err = true;
          data = xhr.response || null;
        }
      }
      callback(err, data);
    };

    // timeout
    timeout = setTimeout(function() {
      xhr.abort();
      callback(true, null);
    }, 10000);

    // start call
    xhr.send();
  }

  // public query method
  return {
    query: query
  };

})();

This code passes queries to the restdb.io API endpoint and sets the appropriate HTTP headers including x-apikey for the API key. It times out if the response takes longer than ten seconds. A callback function is passed an error and any returned data as a native object. For example:

// run a query
restDB.query(
  '/content?q={"published":true}',
  function(err, data) {
    // success!
    if (!err) console.log(data);
  }
);

The console will output an array of documents from the content collection, e.g.

[
  {
    _id: "1111111111111111",
    slug: "",
    title: "Home page",
    body: "page content...",
    image: [],
    published: true
  },
  {
    _id: "22222222222222222",
    slug: "page-two",
    title: "Page Two",
    body: "page content...",
    image: [],
    published: true
  },
  {
    _id: "33333333333333333",
    slug: "page-three",
    title: "Another page",
    body: "page content...",
    image: [],
    published: true
  }
]

The API can be called from any language which can make an HTTP request. restdb.io provides examples for cURL, jQuery $.ajax, JavaScript XMLHttpRequest, NodeJS, Python, PHP, Java, C#, Objective-C and Swift.

I’ve created a simple example at Codepen.io which allows you to search for strings in the title and body fields and displays the results:

See the Pen restdb.io query by SitePoint (@SitePoint) on CodePen.

It passes the following query:

{ "$or": [
  { "title": {"$regex": "searchstring"} }, 
  { "body":  {"$regex": "searchstring"} }
]}

where searchstring is the search text entered by the user.

An additional h querystring parameter limits the returned fields to just the slug, title and published flag:

{
  "$fields": {
    "slug": 1,
    "title": 1,
    "published": 1
  }
}

Further information:

Step 7: Build Your Own CMS

A few steps were required to create a database-driven website and a simple search facility. You could edit pages directly using restdb.io’s user interface but it would be possible to build a bespoke CMS to manipulate the content. It would require:

  1. A new restdb.io API key (or change the existing one) to have appropriate GET, POST, PUT, PATCH and DELETE access to the content collection.
  2. A user interface to browse or search for pages (the one above could be a good starting point).
  3. A process to start a new page or GET existing content and place it in an editable form.
  4. Processes to add, update or delete pages using the appropriate HTTP methods.

The editing system should run on a restricted device or behind a login to ensure only authenticated users can access. Take care not to reveal your restdb.io API key if using client-side code!

Further information:

Try restdb.io Today!

This article uses restdb.io to build a rudimentary CMS, but the service is suitable for any project which requires data storage. The REST API can be accessed from any language or framework which makes it ideal for applications with multiple interfaces, e.g. a web and native mobile view.

restdb.io provides a practical alternative to managing your own database software installation. It’s simple to use, fast, powerful, highly scalable and considerably less expensive than hiring a database expert! Your application hosting costs will also reduce since all data is securely stored and backed-up on the restdb.io servers.

Finally, restdb.io makes you more productive. You can concentrate on the main application because data storage no longer causes concerns for you and your team.

Start building your restdb.io database today and let us know how you get on!

Continue reading %How to Get Started With restdb.io and Create a Simple CMS%


Source: Sitepoint

Frame by Frame Animation Tutorial with CSS and JavaScript

Frame by frame animation with HTML, CSS and JavaScript

Imagine your designer asked you to implement a beautiful frame by frame animation for the awesome project you’ve been working on. As the front-end dev on the project, not only is it up to you to come up with a working animation, but also to deliver a silky smooth, performant and maintainable frame by frame animation that works great across different browsers, both on desktop and mobile.

This tutorial shows you the various ways you can create this type of animation with HTML, CSS, and JavaScript, while improving on each iteration to achieve the best result for your project.

What Is a Frame by Frame Animation?

According to this definition by Adobe, a frame by frame animation:

… changes the contents of the Stage in every frame. It is best suited to complex animation in which an image changes in every frame instead of simply moving across the Stage.

In other words, the subject of the animation is represented in a set of images. Each image in the set occupies an animation frame, and the rate of change with which each frame replaces the next produces the illusion of motion in the image.

I will demonstrate the whole workflow as you’ll be working on this great blinking eye animation from Zeiss website.

This is the set of images you’ll be using to build the animation frames:

Blinking eye sprite for frame by frame animation

And here’s the final result:

Blinking eye frame by frame animation

For this tutorial, I’ve chosen to use SVG images because they are great at scaling with different screen sizes for responsive web design. However, if for whatever reason you don’t want to use SVG graphics, you can create web animations with PNG, JPEG, and GIF image formats or use HTML5 Canvas. I will share my thoughts on these alternatives at the end of the article.

For simplicity’s sake, in this tutorial you’ll be using the jQuery library and have Autoprefixer up and running, therefore the code will be free of browser-specific CSS prefixes.

Now, let’s do some coding!

1 — Frame by Frame Animation by Changing the Image’s Source

The first option is straightforward enough, and that’s one reason why I like it.

In your HTML document, create an img element, which acts as container for the images, one at a time, as each animation frame is replaced by the next:

[code language=”html”]
<img class=”eye-animation”
src=”https//helpx.adobe.com/images/Eye-1.svg”
alt=”blinking eye animation”/>
[/code]

The CSS:

[code language=”css”]
.eye-animation {
width: 300px;
}
[/code]

The next step is to replace the existing image with the next one over a period of time dynamically, so as to create the illusion of movement.

You could do it with setTimeout but it’s better to use requestAnimationFrame. Doing so has some advantages from the point of view of performance. For example:

  • The quality of other animations on the screen won’t be affected
  • The browser will stop the animation if users navigate to another tab.

Here’s the jQuery code:

[code language=”js”]
const $element = $(‘.eye-animation’);
const imagePath = ‘/images’;
const totalFrames = 18;
const animationDuration = 1300;
const timePerFrame = animationDuration / totalFrames;
let timeWhenLastUpdate;
let timeFromLastUpdate;
let frameNumber = 1;

function step(startTime) {
if (!timeWhenLastUpdate) timeWhenLastUpdate = startTime;

timeFromLastUpdate = startTime – timeWhenLastUpdate;

if (timeFromLastUpdate > timePerFrame) {
$element.attr(‘src’, imagePath + `/Eye-${frameNumber}.svg`);
timeWhenLastUpdate = startTime;

if (frameNumber >= totalFrames) {
frameNumber = 1;
} else {
frameNumber = frameNumber + 1;
}
}

requestAnimationFrame(step);
}
[/code]

When the page loads, you call requestAnimationFrame for the first time and pass the step function to it, together with the animation’s startTime parameter built into the requestAnimationFrame function.

At each step the code checks how much time has passed from the last image source update and, if it’s longer than the required time per frame, then it refreshes the image.

Because you’re building an infinite animation, the code above checks if it’s got to the last frame and if so, it resets the frameNumber to 1; if not, it increases the frameNumber by 1.

Images should have the same name structure made of an increasing number series and the same location (e.g., images/Eye-1.svg, images/Eye-2.svg, images/Eye-3.svg, etc.) so that the code can easily iterate through them.

Finally, call requestAnimationFrame again to continue the whole process.

It looks good. However, if you try this you’ll see it won’t work because when the animation starts, only the first image gets loaded. The reason for this is that the browser knows nothing about the images you want to display until the code updates the image element’s src attribute in the middle of the animation loop. For a smooth animation, you need to preload the images before the loop starts.

There are different ways you can do this. Here’s the one I like best. It consists in appending hidden divs and setting their background-image property to point to the required images.

The jQuery code:

[code language=”js”]
$(document).ready(() => {
for (var i = 1; i < totalFrames + 1; i++) {
$(‘body’).append(`<div id=”preload-image-${i}” style=”background-image: url(‘${imagePath}/Eye-${i}.svg’);”></div>`);
}
});
[/code]

Here’s the full working demo on CodePen:

See the Pen Frame by frame-animation-1-source by SitePoint (@SitePoint) on CodePen.

Below I’ve listed some pros and cons to this approach.

Cons:

  • With HTTP v1.1, having to load multiple images can significantly increase page load time on the first visit
  • The animation can be janky on mobile devices. That’s because the browser has to perform a repaint each time the image element’s src attribute is updated (please check out Paul Lewis’ blog post for the details).

Pros:

  • Declarative — the code just iterates through the set of images
  • The image is fixed in one place — no jumping back and forth is visible (you’ll see why this is important below).

2 — Frame by Frame Animation by Changing the Image’s Opacity

To avoid browser repaints, you could change the images’ opacity instead of changing their source.

You could render all the images with opacity: 0 at page load and then set opacity: 1 for exactly when you want to show that frame.

That would improve rendering performance, but you’ll still have to preload all the images up front (which could be tricky if you have other images on the page as well and don’t want to wait for all of them to load). Also, because of multiple images, you’ll still have a longer first-time page load duration.

Here’s the full code:

You can avoid HTML code duplication by leveraging the capabilities of template engines such as Pug, Twig, React, Angular etc., or by just appending the divs using JavaScript as you did in the previous example.

3 — Frame by Frame Animation by Changing the Sprite’s Position

The usual workaround to prevent having to download multiple images consists in using an image sprite.

So, let’s do that.

Continue reading %Frame by Frame Animation Tutorial with CSS and JavaScript%


Source: Sitepoint

How Nostalgia in Web Design Captivates Users (with examples)

Vintage photography

Nostalgia makes users feel warm inside. Suzanne Scacca explains the user psychology behind this, and how we can utilize the effects of nostalgia in web design on users for higher conversions and engagement (with examples).

———

Right now, more than ever before, we’re seeing all sorts of nostalgic throwbacks causing us to reminisce about the good ol’ days! We’re seeing an endless supply of remakes, reboots and long-awaited sequels like Spider-Man and Ghostbusters; Bruno Mars topping the music charts with songs that sound eerily similar to classic hits by Kool & the Gang; women wearing chokers and high-waisted pants.

And this isn’t a new phenomenon either.

Every generation daydreams about how things were way back when, and what’s changed since.

It’s true, nostalgia is a very powerful emotion. It can even make us feel happy and at the same time, and in design/marketing, we can use nostalgia to captivate users…then convert them.

What the Research Says About Nostalgia

Nostalgia stirs up very strong feelings, so there’s something to be said about user psychology and why we continue to see retro throwbacks time and time again. After all, the goal in marketing is to create content that taps into our audience’s emotional core and establishes a much deeper connection with them far beyond a superficial “Buy 1, Get 1 Free” offer.

Nostalgia achieves that well.

So. Jumping on the retro bandwagon: is it really worth it when “comebacks” tend to have such a short-term expiration?

Yes.

Studies suggest that not only are nostalgic marketing angles captivating to audiences, simply for the reminiscent feelings accosted with them, but retro visual aesthetics can boost these effects even further, and that’s where design comes into it. Let’s take a closer look at what exactly happens when we feel nostalgic.

Nostalgia in web design makes visitors feel more connected

Dr. Filippo Cordaro, a researcher of nostalgia from the University of Cologne, found similarities between an individual reminiscing about the past and the level of social connectivity they felt. He explains:

“On a basic level, recalling these positive memories simply puts us in a more positive mood. On a more complex level, recalling these experiences makes us feel a stronger sense of social connectedness with others.”

Positive feelings and nostalgia

It’s the latter half of this conclusion that’s most important for marketers and web designers to understand; that feeling of “connectedness” is what we should be striving for, and we can do this by telling stories through visual design and using imagery that visitors can relate to. While a superficial offer/discount might grab the user’s attention momentarily, digging deeper into the audience’s emotional core and establishing a more genuine, heartfelt connection is more effective overall.

In short: nostalgic hooks are more memorable because they’re based on experiences familiar to the visitor.

Real Examples (and what we can learn from them)

If you’re curious to see how you might use nostalgic hooks in visual design and communication, then check out what these brands have done and the effects they’ve had.

Danner

Overall, the vintage-style typography and classic insignia-style details compliment the (more modernized) minimal/flat approach to the layout, where the two styles come together to convey the vintage brand that is Danner’s boots. Danner’s was founded in 1932, so you could say that the visual aesthetic is a modern twist on a vintage brand that customers already know and love. You have to stay true to your roots (as they say), but you also have stay with the times. Danner’s Boots does both.

Also, as you may have noticed, brown/beige colors are quite common in vintage visual aesthetics. Color can also play a huge role in influencing how users feel.

Danner's Boots

Desires Tram

Desires Tram is another web design example where mixing somewhat minimalistic layouts with vintage details has worked well. What we can take away from this is that serif fonts can still be bold, and bitmap images don’t have to impact loading times too much if used sparingly. Overall, these design elements, the “mascot” character and the magical sounds strike a wonderful blend of creativity and nostalgia like something straight out of Harry Potter.

Robby Leonardi

Retro video games. Now we’re getting to closer to the heart, because this is more likely to be “your era”. I wouldn’t be surprised if developer Robby Leonardi’s interactive resume resonates with you more than the first two examples, because retro video games are more likely take you back to your childhood (well…it depends how old you are I suppose!).

Brown/beige/grunge/vintage styles are certainly captivating and may induce feelings of nostalgia from a visual perspective, but it’s not something that’s likely resonate with you from an emotional angle (not unless you’re into vintage things, which you may very well be).

Even those that didn’t play old-school Nintendo games will undoubtedly recognize the “game” as a Super Mario-style game, so this is a type of nostalgia that won’t be lost on many users. It definitely takes me back and ultimately gets me to stick around his website a little longer.

Robby Leonardi

St. Louis Browns Historical Society

St. Louis Browns Historical Society is a terrific example of a website that makes use of real life footage. The home video approach intentionally touches the heart, and the rest of the website continues with some of the visual details we’ve seen in the other examples: grungey visuals and serif fonts combined with flat elements and sans-serif fonts, a perfectly executed combination of vintage and modern that lets retro designs work on the web today.

Continue reading %How Nostalgia in Web Design Captivates Users (with examples)%


Source: Sitepoint

Securing Your Website with HTTPS Is More Important than Ever

Securing Your Website with HTTPS Is More Important than Ever

There’s been a huge movement to make the web secure in recent days and this is mostly due to the consequences of not securing your site.

If you have a website, or you’re thinking about deploying your site soon, you need to consider making it work with HTTPS.

Now, before we go over the issues of not having a secure site (spoiler alert: it’s a big deal even if you ignore the security concerns), let’s go over how many sites are using HTTPS as of mid-2017.

According to Firefox’s telemetry data, ~60% of page views are being loaded over HTTPS:

Securing Your Website with HTTPS Is More Important than Ever

That shows about a +20% adoption rate in 18 months, which is very impressive considering that accounts for all page views on the internet, not just page views on top sites.

Chrome’s telemetry data is in the same ballpark as Firefox:

Securing Your Website with HTTPS Is More Important than Ever

Why Is Everyone Scrambling to Secure Their Site?

The reality is, hosting an insecure site just isn’t good enough…

  • Google ranks insecure pages (HTTP) worse than secure pages (HTTPS)
  • Your visitor’s browsing activity and data isn’t encrypted or protected
  • Chrome and Firefox are ​adding scary visual cues to punish insecure sites. That means, even non-technical folk are now receiving in your face warnings that your site is dangerous to view…

Securing Your Website with HTTPS Is More Important than Ever

It started with the secure lock icon, but that’s old news. Browser vendors have been doing that for years.

Recently, they have been rolling out more aggressive cues, and it’s going to continue to get worse and worse for insecure sites as time goes on.

A few current and upcoming visual cues in Chrome and Firefox:

Securing Your Website with HTTPS Is More Important than Ever

Firefox is already showing the visual cues on the right, and Chrome is about to transition to using a non-red “Not secure” label in October 2017, with the red version coming eventually.

Even a non-technical user can see that it’s bad and dangerous.

These are in your face warnings that your site is not secure. I don’t know about you, but there’s no way in heck that I would consider putting sensitive information into an insecure form.

Insecure Sites Let Anyone Who Is Watching View Your Browsing Habits

I don’t even like browsing anonymously on insecure sites because that means all of your browsing habits can be spied on by your ISP (Internet Service Provider) or anyone watching. With net neutrality constantly being attacked, this is a big deal and ultimately affects everyone in the world.

As website owners, we can do our best to secure the web one site at a time by simply securing our sites over HTTPS. It’s not a war that we can’t win either. We are winning (world wide HTTPS coverage is over 50%)!

Continue reading %Securing Your Website with HTTPS Is More Important than Ever%


Source: Sitepoint