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

Designing The Perfect Feature Comparison Table




 


 

Not all products are created equal. While we repeatedly buy some products almost mindlessly, for others, we take a lot of time to make a purchasing decision. For a price tag that meets a certain threshold or if we are particularly invested in the quality of a product, we want to be absolutely certain that we are making the right choice and are getting a good product for a good price. That’s where a feature comparison table makes all the difference.

Designing The Perfect Feature Comparison Table

Feature comparison tables are helpful not only in their primary function, though. When designed properly, they can aid in decision-making way beyond placing product specifications side by side. They can also add meaning to an otherwise too technical product specification sheet, explaining why a certain feature is relevant to the customer or how a certain product is better than the others.

The post Designing The Perfect Feature Comparison Table appeared first on Smashing Magazine.


Source: Smashing Magazine

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

The Nine Principles Of Design Implementation




 


 

Recently, I was leading a training session for one of our clients on best practices for implementing designs using HTML and CSS. Part of our time included a discussion of processes such as style-guide-driven development, approaches such as OOCSS and SMACSS, and modular design. Near the end of the last day, someone asked, “But how will we know if we’ve done it right?

The Nine Principles Of Design Implementation

At first, I was confused. I had just spent hours telling them everything they need to “do it right.” But after thinking about it, I realized the question was rooted in a deeper need to guide and evaluate what is often a set of subjective choices — choices that are sometimes made by a lot of different people at different times.

The post The Nine Principles Of Design Implementation appeared first on Smashing Magazine.


Source: Smashing Magazine

Pagination in CodeIgniter: The Complete Guide

The benefit of using any full-stack web application framework is that you don’t have to worry about the common tasks like input handling, form validation and the like, as the framework already provides wrappers for those features. Thus, it allows you to concentrate on the business logic of the application rather than reinventing the wheel over and over again.

Today, we’re going to explore an important library in the CodeIgniter framework—the pagination library.

Let me highlight the topics that we’re going to cover in the course of this article:

  • Demonstration of basic paging
  • Explore the customization options
  • Pagination configuration

Demonstration of Basic Paging

In this section, we’ll go through an example that demonstrates the use of pagination in CodeIgniter. It’s the best way to understand how things work altogether.

In our example, we’ll build a pretty simple user listing in which we’ll fetch records from the users MySQL table. In order to successfully run this example, make sure that you have the uid and uname fields in your users table.

With that set up, we’re ready to roll.

Go ahead and create a controller file controllers/Paging.php with the following contents.

Next, we’ll need a model file models/Users.php that fetches records from the users table.

Finally, let’s create a view file at views/user_listing.php that displays the user listing.

Now, go ahead and access our custom page at http://your-code-igniter-site/paging/index and you should see the user listing along with the pagination! So, that’s it, we’ve done it! Don’t worry, I won’t leave you that soon, as we’ll start dissecting each part of the code now.

We’ll start with the model file models/Users.php as that’s something will be called from our controller methods. There are two important methods, get_current_page_records and get_total, that our model implements in order to build the pagination links.

Let’s go through the get_total method. It’s used to count the number of records in the users table.

Next, there’s a get_current_page_records method.

There are two important arguments that you should note in the get_current_page_records method. The first argument, $limit, is used to specify the number of records that will be returned during the query run. And the second argument, $start, acts as the starting index of the record.

So, as you can see, given the values of $start and $limit we can fetch records by page. That’s the essence of paging, and meanwhile we’ve implemented the most important method of this article!

So, that was our model—simple and elegant!

Moving ahead, let’s switch our attention to the controller file. Go ahead and grab the code of the constructor method.

In order to use pagination in CodeIgniter, the first thing you need to do is to load the pagination library. And we can do it by using $this->load->library('pagination').

We’ve also loaded the URL helper so that we can use global helper functions provided by that helper.

Now, we’re ready to go through the heart of our controller—the index method.

To start with, we make sure that the database is loaded properly. Following that, we load the Users model so that we can use the model methods.

Next, we initialize a couple of important variables.

The variable $limit_per_page defines the limit per page. Of course, you could set it as you wish; it’s set to 1 at the moment for example purposes.

The $start_index variable holds the starting index of the MySQL record. When CodeIgniter builds the pagination links, it appends the starting index of the page as the third segment in the URL by default. You can change this default behavior, but that’s something we’ll reserve for the last section of this article, where we’ll discuss customization options.

Finally, we call the get_total method of the Users model to get the total records of the users table, and it’s assigned to the $total_records variable.

Next, we fetch the records of the current page using the get_current_page_records method.

Before we can actually go ahead and build pagination links, we need to initialize the minimal paging configuration using the initialize method of the paging library.

And that’s the set of minimum parameters to build the pagination links.

  • base_url: The URL that will be used while building pagination links
  • total_rows: Total number of records
  • per_page: Record count per page

Finally, we use the create_links method to build pagination links.

The rest is just the formality to call our view user_listing and render the output! Run the URL http://your-code-igniter-site/paging/index to see the user listing along with the pagination links.

So that’s a very simple yet useful pagination example at your disposal that you could extend to fit your requirements.

In the next section, we’ll explore how you could customize the default pagination in terms of appearance and functionality.

Explore Customization Options

In this section, we’ll explore the options available that you could use should you wish to customize the default pagination links.

URI Segment

Although the CodeIgniter paging library automatically detects the paging-related parameter from the URL, you could define a custom value if you have different URL pattern.

Number of Digit Links

The num_links option allows you to define the number of digit links that will be displayed before and after the active page number in the pagination links.

Page Number as URI Segment

When you access the paging URI segment, it’s a starting index by default. For example, if you have ten records per page, the paging URI segment is 20 for the third page. Instead, if you want to show actual page numbers in the paging links, you can set use_page_numbers to TRUE.

Of course, you need to make sure that you calculate the proper starting index based on the page number you retrieve from the URL.

Preserve Query String

More often than not, you end up in the situation where you want to preserve query string parameters that are not related to pagination. You can use the reuse_query_string option to enable that facility.

These were a few options that you could use to alter the default pagination functionality. Next, we’ll look at a couple of other options that allow you to alter the way pagination links are displayed.

Wrapper Tag

If you want to wrap the pagination code with any other HTML tag then you could do it using the full_tag_open and full_tag_close options.

It could be really useful should you wish to apply custom styling to the pagination links.

First, Last, Next, and Previous

If you want to change the text that will be displayed for the first, last, next and previous links, you could do that as well.

Also, if you want to wrap those individual links with any HTML tag, you could do that in the same way as we did it to wrap the whole paging code.

Active Link and Number Link

Sometimes, you want to style the active link differently. You could do that by applying wrapper tags as shown below.

In the same way, if you want to wrap digit links with something:

And that ends the story of customization. In fact, you could go ahead and look at the customization example at http://your-code-igniter-site/paging/custom that’s already included in our controller file!

Paging Configuration

Now you’re aware of the configuration that’s required to set up a decent pagination with any model listing. And most of the time, you want to keep it the same throughout the site. What are you going to do to achieve that? You might be tempted to copy the configuration code and paste it into each action that requires the pagination configuration.

In fact, there’s a better way you could handle this scenario. You can create a paging configuration file at application/config/pagination.php and use the $config variable to define your settings.

Based on that, the revised index action method should look like this:

Of course, the total_rows and base_url variables change from action to action, so you need to set them explicitly in every action.

To accomplish that, you need to load the pagination configuration in the first place.

Next, you can override the action specific settings.

And you’re done with that!

So that was the story of the pagination configuration, and that ends this article as well!

Conclusion

Today, we went through the pagination library in CodeIgniter.

In the first part of this article, I demonstrated how you can use the pagination library by providing a very simple yet useful example.

Following that, we discussed the customization options that are available at your disposal while setting up the pagination.

Finally, we discussed the pagination configuration in the last section.

CodeIgniter is a powerful PHP platform. Whether you’re just getting started or you’re starting with the next version, don’t forget to check out what we have available for you, as well.

I would love to know your feedback in the form of queries and comments using the feed below!


Source: Nettuts Web Development

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

JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG

After completing the first three tutorials of the series, you should now be very comfortable with a lot of Anime.js features. The first tutorial showed you how to select target elements. In the second tutorial, you learned about different types of parameters that can be used to have fine control over the delay and duration of animations of different elements. The third tutorial focused on learning how to have greater control over the values of a single property during the course of the animation.

In this tutorial, you will learn about different callbacks that can be used to execute a function based on the progress of the animation. Almost every example in the previous tutorials used CSS properties to demonstrate how different methods and parameters work. This might have given you the idea that the library is more suited for animating CSS properties. This time, we will have a section dedicated to the creation of interesting SVG-related animations in Anime.js.

Callbacks

As I mentioned in the introduction, you can use callbacks to execute functions based on the progress of the animation. There are four different callbacks: begin, run, update, and complete. Each callback function is fired at a specific time, and each one accepts an animation object as its argument. 

The begin() function is called when the animation actually begins. This means that if an animation has a delay of 800ms, begin() will be called only after that delay is over. You can check if an animation has begun playing or not using animationName.begin, which will return true or false respectively.

The run callback can be used to execute a function in every frame after an animation actually starts playing. If you want to execute a function in every frame from the very beginning of the animation irrespective of its delay, you should use the update callback instead.

The complete callback is similar to begin except for the fact that it is called once the animation has finished playing. Just like begin, you can use animationName.complete to check if an animation has finished playing or not.

You have already seen in the first tutorial how to use the update callback while animating numerical values of a JavaScript object. In this tutorial, we will modify that example and see how to use all these callbacks together to provide more information to the user.

I have intentionally added some delay in this animation so that we can notice the difference in the timing of the execution of different callbacks. The update callback starts executing its function as soon as the animation instance begins. 

The actual animation starts playing after 1000ms, and that’s when the begin function shows its “Starting the Scan…” message to the user. The run function also starts executing at the same time and updates the numerical values of the object after every frame. Once the animation has finished, the complete callback shows a “Scan Complete…” message to the user.

Easing Functions

Easing functions can be used to control how the value of a property transitions from its initial value to its final value. These easing functions can be specified using the easing parameter, which can accept strings as well as custom Bézier curve coordinates (in the form of an array). 

There are 31 different built-in easing functions. One of them is linear, and the other 30 consist of ten different variations of easeIn, easeOut, and easeInOut. There are three elastic easing equations called easeInElasticeaseOutElastic, and easeInOutElastic. You can control their elasticity using the elasticity parameter. The value of elasticity can be anywhere between 0 and 1000.

EaseIn equations accelerate the value change of the property starting from zero. This means that the change in value would be slow in the beginning and very quick at the end. The rate of change is zero in the beginning and maximum at the end. EaseOut equations decelerate the value change of the property starting from the maximum rate change. 

This means that the change in value would be very quick in the beginning and very slow at the end. EaseInOut equations accelerate the rate change in the beginning and decelerate it at the end. This means that the rate of change will be slow in the beginning as well as the end, and it will be fastest in the middle of the animation. The following demo shows the difference in the rate of change for each of these easing functions.

You can also add your own custom easing functions to the built-in list with the help of anime.easings. Here is an example of creating custom easing functions.

SVG-Based Animations

All the motion-related animations that we have created until now moved the target elements in straight lines. It is also possible in Anime.js to move an element along a complex SVG path with lots of curves. You can control both the position and the angle of the animating elements on the path. To move an element to the x coordinate of the path, you can use path(x). Similarly, an element can be moved according to the y coordinate of the path using path(y)

Unless the path is a straight line, it will almost always form an angle with respect to the horizontal base line. If you are rotating any non-circular element, it will feel more natural if the element follows the angle of the path. You can do so by setting the rotate property to be equal to path('angle'). Here is the code that animates four elements with different easing values along an SVG path.

You can see in the following demo that the red square with easeInCubic easing is slowest in the beginning and the fastest at the end. Similarly, the orange square with easeOutCubic is the fastest in the beginning and the slowest at the end.

You can also animate the morphing of different SVG shapes into one another using Anime.js. The only condition is that both the shapes should have the same number of points. This means that you can only morph triangles into other triangles and quadrilaterals into other quadrilaterals. Trying to morph between an unequal number of polygon points will result in an abrupt shape change. Here is an example of morphing a triangular shape.

One more interesting effect that you can create with SVG is line drawing. All you have to do is give Anime.js the path that you want to use for line drawing and other parameters that control its duration, delay, or easing. In the following demo, I have used the complete callback to fill the line drawing of the Font Awesome anchor icon with a yellow color.

Combining the knowledge of all the concepts that you have learned so far, you can create more complex line drawings with much better control over the way they are drawn. Here is an example in which I have written my own name using SVG.

I begin by assigning the value 2000 to the variable letterTime. This is the time that I want Anime.js to take while it draws each letter of my name. The delay property uses the function-based index parameter to set an appropriate delay value with the help of the letterTime variable. 

The index of the first letter “M” is zero, so Anime.js starts drawing it immediately. The letter “O” has a delay of 2000ms because that’s the amount of time it takes to completely draw the letter “M”.

Inside the begin callback, I have set the stroke value of all the letters to black and their fill values to none. This way we can clear all the color values applied inside the update callback so that the letters can return to their initial state when run in multiple loops. Try clicking the Write the Name button in the following demo to see the code in action.

Final Thoughts

In this tutorial, you learned about different callback functions that can be used to perform tasks like updating the DOM or changing the value of an attribute based on the animation progress. You also learned about different easing functions and how to create one of your own. The final section of the tutorial focused on creating SVG-based animations.

After completing all four tutorials of the series, you should now have enough knowledge of Anime.js to create some interesting effects for your next project. If you have any questions related to this tutorial, please let me know in the comments.


Source: Nettuts Web Development