Posts Tagged ‘php’

Handle Mouse And Touch Input With The Pointer Events API

Tuesday, April 18th, 2017

pointer-events-api-2

With more and more people using their mobile phones and tablets for web browsing, we as developers have to make sure that our web interfaces are fully accessible via touch. Setting up click and hover event listeners sort of works, but it is clearly a leftover solution from the mouse era.

Thankfully, there is a new API in town that accommodates the needs of mouse, touch, and stylus devices. It’s called Pointer events (not to be mistaken with the CSS property of the same name) and it allows us to add event listeners that are better suited for working with all types on input.

Meet The New Events

The new Pointer Event API is an evolved version of the Mouse Event interface we’ve all been using so far. It extends the functionality of the old API and adds support for multi-touch gestures, precise pen input, and overall smoother touchscreen interaction.

Most of the Pointer Events have direct alternatives among the old mouse events. Once the new API gets full browser support we can directly substitute with the more modern alternatives:

const button = document.querySelector("button");

// Instead of mouseover
button.addEventListener('mouseover', doSomething);

// We can use pointerover
button.addEventListener('pointerover', doSomething);

Interacting with a mouse should be the same in both cases. Using fingers or a stylus, however, will be easier to program with the new API.

Recognizing Input Type

An awesome feature of the Pointer Events API is that it can tell which type of input has been used. This can be helpful when you want to ignore some of the input methods or provide special feedback for each one.

button.addEventListener('pointereover', function(ev){
  switch(ev.pointerType) {
    case 'mouse':
      // The used device is a mouse or trackpad.
      break;
    case 'touch':
      // Input via touchscreen.
      break;
    case 'pen':
      // Stylus input.
      break;
    default:
      // Browser can't recognize the used device.
      break;
  }
});

Other Properties

The Pointer Events interface provides some some other interesting data as well. It includes all the MouseEvent properties plus the following:

Mouse clicks always have a width and height of 1, touch size differs.

Mouse clicks always have a width and height of 1 while touch size varies.

Browser Support

Pointer Events are fairly new, so browser compatibility isn’t perfect yet. Chrome (desktop and mobile), Edge, IE, and Opera have full support; Firefox and Safari don’t.

Pointer Events Browser Compatibility on Can I Use

Pointer Events Browser Compatibility on Can I Use

To check whether a browser has the Pointer Events API you can use the window object:

if (window.PointerEvent) {
  // Pointer Events enabled.
} else {
  // Pointer Events not supported
}

A popular open-source pollyfill is also available for those who don’t want to wait for full browser adoption.

Conclusion

Although it doesn’t have full browser support yet, the Pointer Events API is eventually going to take over the old mouse events. It provides a lot of cool features that will increase web accessibility and enable developers to create more advanced touch and stylus-based apps.

If you want to learn more about the Power Events API we recommend checking out these resources:

Tags: , , , ,
Posted in PHP Tutorials | No Comments »

Learn Webpack in 15 Minutes

Monday, April 10th, 2017

learn-webpack-in-15

Build tools have become an integral part of web development, mainly due to the ever-increasing complexity of JavaScript apps. Bundlers allow us to package, compile, and organize the many assets and libraries needed for a modern web project.

In this tutorial we will take a look at webpack, a powerful open-source bundler and preprocessor that can handle a huge variety of different tasks. We’ll show you how to write modules, bundle code, and use some of the loader plugins. The tutorial is designed for total beginners to webpack, but having some JavaScript knowledge is advised.

webpack-logo

Why webpack?

Much like any other aspect of web development, there isn’t a standard for which build tool to use. Right now, developers have to choose between webpack, Gulp, Browserify, NPM scripts, Grunt, and like 10 others. There are many in-depth comparisons out there, but all of these tools are very similar, so most of the time it comes down to personal preference and what project you are working on.

Here are some pros and cons to help you decide whether webpack is the tool for you:

Pros:

Cons:


1. Installation

The easiest way to install webpack is by using a package manager. We will go with npm but feel free to use Yarn or another hip alternative. In both cases you need to have Node.js on your machine and a package.json ready to go.

It is preferred to install it locally (without the -g tag). This will make sure everyone working on your project has the same version of webpack.

npm install webpack --save-dev

Once we have it installed, it’s best to run webpack via a Node.js script. Add these lines to your package.json:

//...
    "scripts": {
        "build": "webpack -p",
        "watch": "webpack --watch"
    },
//...

Now by calling npm run build from the terminal we can make webpack bundle our files (the -p option stands for production and minifies the bundled code). Running npm run watch will start a process that automatically bundles our files when any of them change.

The last part of the setup is to tell webpack which files to bundle up. The recommended way to do this is by creating a config file.


2. Webpack Config File

Here we will look at the config file in its most basic form but don’t let that fool you – the webpack config file is quite powerful, varies a lot from project to project, and can become super complex in some cases.

In the root directory of your project add a file called webpack.config.js.

webpack.config.js

var path = require('path');

module.exports = {
  entry: './assets/js/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

The entry option tells webpack which is our main JavaScript file. There are many different strategies for configuring entry points but in most cases a single entry is enough.

In output we specify the name and path of our bundle. After running webpack we will have all our JavaScript in a file called bundle.js. This is the only script file that we will link in our HTML:

<script src="./dist/bundle.js"></script>

This setup should be enough to get us started. Later we will add some more stuff to it, but first let’s see how modules work.


3. Webpack Modules

Webpack provides multiple ways to work with modules, and most of the time you are free to go with whichever one you like. For this tutorial we will use the ES6 import syntax.

We want to add a module that greets our users. We create a file called greeter.js and make it export a simple function:

greeter.js

function greet() {
    console.log('Have a great day!');
};

export default greet;

To use this module, we have to import it and call it in our entry point, which if you look back at the config file is index.js.

index.js

import greet from './greeter.js';

console.log("I'm the entry point");
greet();

Now when we run the bundler with npm run build, and open our HTML in the browser, we see this:

console-greet

Our entry point and our greeter module were compiled into one file called bundle.js and it was executed by the browser. Here is a simple flow chart of what’s happening so far:

webpack-flow-1


4. Requiring Libraries

We want our app to specify which day of the week it is when it greets users. To do so we will use moment.js by directly importing it into our greeter module.

First we need to install the library via npm:

npm install moment --save

Then in our greeting module, we simply import the library exactly the same way we imported local modules in the previous point:

greeter.js

import moment from 'moment';

function greet() {
    var day = moment().format('dddd');
    console.log('Have a great ' + day + '!');
};

export default greet;

After we bundle up again to apply the changes, in the browser console we will have the following messages:

weekday-greet

Our flow diagram now looks like this:

webpack-flow-2

Note: There are other, more advanced techniques for including libraries but they are outside the scope of this article. You can read more about them here.


 5. Loaders

Loaders are webpack’s way to execute tasks during bundling and pre- or post-process the files in some manner. For example, they can compile TypeScript, load Vue.js components, render templates, and much more. Most loaders are written by the community, for a list of popular loaders go here.

Let’s say we want to add a linter to our project that checks our JS code for errors. We can do so by including the JSHint loader, which will catch all kinds of bad practices and code smells.

First we need to install both JSHint and the webpack JSHint loader:

npm install jshint jshint-loader --save

Afterwords, we are going to add a few lines to our webpack config file. This will initialize the loader, tell it what type of files to check, and which files to ignore.

webpack.config.js

var path = require('path');

module.exports = {
  entry: './assets/js/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  // Add the JSHint loader
  module: {
    rules: [{
      test: /\.js$/, // Run the loader on all .js files
      exclude: /node_modules/, // ignore all files in the node_modules folder
      use: 'jshint-loader'
    }]
  }
};

Now when webpack is started, it will show us a list of warnings in the terminal (which we will ignore):

terminal-warnings

Since moment.js is located in the node_modules folder, it won’t be linted by the JSHint loader:

webpack-flow-3


Further Reading

This concludes our introduction to webpack! Since this is a lesson for beginners, we tried to cover only the most useful and must-know concepts of webpack. We hope the tutorial has been helpful, not too confusing, and within the 15 minute limit from the title.

In the near future, we are planning to add a second part to this tutorial, explaining how to work with CSS modules and other more-advanced features. In the meantime, if you want to learn more about webpack (and there is a lot more) we recommend checking out these awesome resources:

Tags: , , , ,
Posted in PHP Tutorials | No Comments »

15 Interesting JavaScript and CSS Libraries for April 2017

Monday, April 3rd, 2017

interesting-libraries-april-2017

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.


Core UI

Core UI

Based on Bootstrap 4, Core UI is an admin template offering a highly customizable solution to building control panels. There are separate boilerplate versions that allow you to quickly integrate it with some of the most popular frameworks right now: AngularJS, Angular 2, React.js, and Vue.js.


React Trend

React Trend

A React component by the Unsplash team that can be used to create beautiful line graphs suitable for displaying trending and activity metrics. This project follows a minimalistic approach and gives you a simple, polished solution to one specific problem, so don’t expect a full charting library. An unofficial Vue port is also available here.


Element

Element

Element is a UI framework based on Vue.js 2.0. It includes a set of over 50 components that are styled very consistently, following certain design and color choices. Each element is well documented and super easy to customize and implement into any Vue.js project. There is also a useful Sketch Template of the components for building mockups.


Extension Boilerplate

Extension Boilerplate

This project provides us with a solid foundation for creating cross-browser extensions. The boilerplate is based on WebExtensions, making it possible to write extensions once, and then deploy them simultaneously to Chrome, Opera & Firefox. It also has other cool features such as live-reload and a bundle of various Sketch assets needed for submitting to the respective app stores.


BigPicture

BigPicture

Modern lightbox plugin that works simultaneously for images and videos, providing smoothly animated overlay pop-ups. An awesome feature of BigPicute is that it works both with <img> tags and with background-image elements, giving developers freedom in their markup. As for the video, YouTube, Vimeo, and direct video links are supported.


Reactive Listener

Reactive Listener

Don’t let the name fool you, this isn’t a React component. Reactive listener is a tiny library by Zurb that allows us to create advanced event listeners that respond to more complex actions than simply clicks and hovers. Right now it can only recognize when the user is moving towards an element, but in the future more cool listeners may be added.


Eagle.js

Eagle.js

Eagle.js is a Vue.js framework for making web-based slideshows, similar to Reveal.js. It supports animations, themes, interactive widgets (for web demos), and makes it easy to reuse components, slides and styles across presentations.


Planck.js

Planck.js

This project is a JavaScript rerwite of the popualr C++ Box2D physics engine, used by game developers for years. Plank.js optimizes the engine for web and mobile browsers, and provides an open-source JavaScript-friendly codebase and API. This way web developers can be more comfortable when making 2D games and other physics related experiments.


Create React Native App

Create React Native App

Following the success of the Create React App boilerplate, here is a tool for making React Native apps without the need for any build configuration. It allows for React Native apps to be set up and tested without having to install Xcode or Android Studio.


Pushy Buttons

Pushy Buttons

A tiny library with CSS-only 3D buttons that have a smooth pushing down effect when pressed. The buttons come in 4 sizes and 3 colors and can be easily customized via SASS or by simply modifying the source .css file.


React Overdrive

React Overdrive allows developers to animate elements on the page and to create smooth transiitons between the different states (or pages) in an app. The API is component based so setting up transitions is super easy, even when switching between multiple JavaScript files.


MoveTo

MoveTo

Our monthly resources compilation wouldn’t be complete without the addition of at least one click-to-scroll animation library. This month we have moveTo – a zero dependency JavaScript library that is only 1kb gzipped, super easy to use, and utilizes the native window.scroll API for doing animations.


Anchorme

Anchorme

Anchorme is a powerful JavaScript library that takes any string or text file and detects all the URLs inside it. It is fast, reliable, and has lots of useful features and customization options. Possible use cases include converting links in a text to clickable HTML <a> tags, extracting URLs from a string, or as a validator for emails, URLs, and IPs.


RPG Awesome

RPG Awesome

Free icon font that is packed with nearly 500 fantasy themed vector icons. It covers everything from weapons and armor to magic and inventory items. RPG Awesome can be used just like any other web icon font (<i class="ra ra-sword"></i>) and is customizable via simple CSS or SASS.


Tent CSS

Tent CSS

Tent CSS is a framework (or as its creators call it a CSS survival kit) that provides you with all the basic necessities needed for building a responsive website. It is very lightweight (only 5kb gzipped), follows the BEM standard, and has a modern flexbox grid for doing layouts.

Tags: , , ,
Posted in PHP Tutorials | No Comments »

Finally! CSS Triangles Without Ugly Hacks

Monday, March 20th, 2017

css-triangles

Anyone who has tried to make HTML upvote arrows, speech bubbles or other pointy elements, knows that in order to create a CSS-only triangle you have to use some sort of hack. The two most popular solutions are to create your triangles out of borders, or to use unicode characters.

We have to admit that both these CSS hacks are pretty clever but they still are terrible solutions, and as such make our code much uglier and less flexible. For instance, we can’t have a triangle with a background image, since borders and characters can only be one color.

Introducing Clip-path

Clip-path is a fairly new addition to the CSS spec that allows us to show only part of an element and hide the rest. Here is how it works:

Let’s say we have an ordinary rectangular div element. You can click Run in the editor below to view the rendered HTML.

(Play with our code editor on Tutorialzine.com)

To make a triangle we will need the polygon() function. It expects as argument comma separated 2D points which will define the shape of our mask. A triangle = 3 points. Try and change the values to see how the shape transforms.

(Play with our code editor on Tutorialzine.com)

Everything inside the path we created stays, everything outside it is hidden. This way we can make not only triangles, but all sorts of asymmetrical shapes that will behave like regular CSS blocks.

The only drawback of this technique is that we have to carefully calculate the coordinates of our points in order to get a good looking triangle.

Still, it’s way better than using borders or ▲.

Browser Support

If you open the caniuse page for clip-path things don’t look very good at first sight, but in reality the property works perfectly fine unprefixed in Chrome and with the -webkit- prefix in Safari. Firefox users have to wait till version 53. IE/Edge is behind the curve as usual but we can expect support sometime in the future.

Further Reading

The clip-path property has many other tricks up its sleeve, including some SVG magic. To find out more about it check out the links below.

Tags: , , ,
Posted in PHP Tutorials | Comments Off on Finally! CSS Triangles Without Ugly Hacks

CSS Grid VS Flexbox: A Practical Comparison

Tuesday, March 14th, 2017

css-grid-vs-flexbox

Not too long ago, the layout for all HTML pages was done via tables, floats, and other CSS properties that were not well suited for styling complex web pages.

Then came flexbox – a layout mode that was specifically designed for creating robust responsive pages. Flexbox made it easy to properly align elements and their content, and is now the preferred CSS system of most web developers.

Now we have a new contender for the best-system-to-build-html-layouts trophy (trophy title is a work in progress). It is the mighty CSS Grid, and by the end of this month, it will be available natively in Firefox 52 and Chrome 57, with other browsers (hopefully) following soon.

A Basic Layout Test

To get a sense of what it’s like to build layouts with each system, we’ve build the same HTML page twice – once with flexbox, and another time with the CSS grid. You can download both projects from the Download button near the top of the article, or inspect them in this online demo:

A stripped-down static page layout

A Stripped-down Static Page Layout

The design is pretty basic – it consists of a centered container, inside of which we have a header, main section, sidebar, and a footer. Here are the main “challenges” that we’ll have to solve, while keeping CSS and HTML as clean as possible:

  1. Position the four major sections of the layout.
  2. Make the page responsive (the sidebar goes below the main content on smaller screens).
  3. Align the contents of the header – navigation to the left, button to the right.

As you can see, for the sake of the comparison we’ve kept everything very simple. Let’s start with problem number one.

Challenge 1: Position The Page Sections

Flexbox Solution

We’ll start off with the flexbox solution. We add display: flex to the container and direction its children vertically. This will position all the sections one under another.

.container {
    display: flex;
    flex-direction: column;
}

Now we need to make the main section and the sidebar stand next to each other. Since flex containers are generally one-directional, we will need to add a wrapper element.

<header></header>
<div class="main-and-sidebar-wrapper">
    <section class="main"></section>
    <aside class="sidebar"></aside>
</div>
<footer></footer>

We then make the wrapper display:flex and flex-direction it in the opposite direction.

.main-and-sidebar-wrapper {
    display: flex;
    flex-direction: row;
}

The last step is to set the size of the main section and the sidebar. We want the main content to be three times the size of the sidebar, which isn’t hard to do with flex or percentages.

.main {
    flex: 3;
    margin-right: 60px;
}
.sidebar {
   flex: 1;
}

As you can see flexbox did pretty well, but we still needed quite a lot of CSS properties + an additional HTML element. Let’s see how the CSS grid will do.

CSS Grid Solution

There are a couple of different ways to use the CSS grid, but we will go with the grid-template-areas syntax, as it seems most suitable for what we are trying to accomplish.

First we will define four grid-area-s, one for each page section:

<header></header>
<!-- Notice there isn't a wrapper this time -->
<section class="main"></section>
<aside class="sidebar"></aside>
<footer></footer>
header {
    grid-area: header;
}
.main {
    grid-area: main;
}
.sidebar {
    grid-area: sidebar;
}
footer {
    grid-area: footer;
}

Then we can set up our grid and assign the placement of each area. The code below may seem quite complicated at first, but once you get to know the grid system it becomes really easy to grasp.

.container {
    display: grid;

    /* 	Define the size and number of columns in our grid. 
	The fr unit works similar to flex:
	fr columns will share the free space in the row in proportion to their value.
	We will have 2 columns - the first will be 3x the size of the second.  */
    grid-template-columns: 3fr 1fr;

    /* 	Assign the grid areas we did earlier to specific places on the grid. 
    	First row is all header.
    	Second row is shared between main and sidebar.
    	Last row is all footer.  */
    grid-template-areas: 
        "header header"
        "main sidebar"
        "footer footer";

    /*  The gutters between each grid cell will be 60 pixels. */
    grid-gap: 60px;
}

And that’s it! Our layout will now follow the above structure, and because of the way we’ve set it up we don’t even have to deal with any margins or paddings.

Challenge 2: Make Page Responsive

Flexbox Solution

The execution of this step is strongly connected to the previous one. For the flexbox solution we will have to change the flex-direction of the wrapper, and adjust some margins.

@media (max-width: 600px) {
    .main-and-sidebar-wrapper {
        flex-direction: column;
    }

    .main {
        margin-right: 0;
        margin-bottom: 60px;
    }
}

Our page is really simple so there isn’t much to rework in the media query, but in a more complex layout there will be lots and lots of stuff to redefine.

CSS Grid Solution

Since we already have the grid-areas defined, we just need to reorder them in a media-query. We can use the same column setup.

@media (max-width: 600px) {
    .container {
	/*  Realign the grid areas for a mobile layout. */
        grid-template-areas: 
            "header header"
            "main main"
            "sidebar sidebar"
            "footer footer";
    }
}

Or, we can redefine the entire layout from scratch if we think that’s a cleaner solution.

@media (max-width: 600px) {
    .container {
    	/*  Redefine the grid into a single column layout. */
        grid-template-columns: 1fr;
        grid-template-areas: 
            "header"
            "main"
            "sidebar"
            "footer";
    }
}

Challenge 3: Align Header Components

Flexbox Solution

Our header includes some links for navigation and a button. We want the nav to be on the left and the button on the right. The links inside the nav have to be aligned properly next to each other.

<header>
    <nav>
        <li><a href="#"><h1>Logo</h1></a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </nav>
    <button>Button</button>
</header>

We’ve already done a similar layout with flexbox in one of our older articles – The Easiest Way To Make Responsive Headers. The technique is really simple:

header {
    display: flex;
    justify-content: space-between;
}

Now the navigation list and the button are properly aligned. All that is left is to make the items inside the <nav> go horizontally. It’s easiest to use display: inline-block here, but since we are going full flexbox, let’s apply a flexbox-only solution:

header nav {
    display: flex;
    align-items: baseline;
}

Only two lines! Not bad at all. Let’s see how CSS grid handles it.

CSS Grid Solution

To split the nav and the button we will have to make the header display: grid and set up a 2-column grid. We will also need two extra lines of CSS to position them at the respective borders.

header{
    display: grid;
    grid-template-columns: 1fr 1fr;
}
header nav {
    justify-self: start;
}
header button {
    justify-self: end;
}

As for the inline links inside the navigation – we couldn’t get it quite right with CSS grid. Here is how our best try looks:

css-grid-header

The links are inline but they can’t be properly aligned, since there isn’t a baseline option like in flexbox’s align-items. We also had to define yet another subgrid.

header nav {
    display: grid;
    grid-template-columns: auto 1fr 1fr;
    align-items: end; 
}

It’s clear that the CSS grid struggled with this part of the layout, but that isn’t too surprising – it’s focus is on aligning containers, not so much the content inside them. It just isn’t meant for doing finishing touches.

Conclusion

If you’ve made it through the whole article (in which case great job!), the conclusion shouldn’t come as a surprise to you. The truth is, there isn’t a better system – both flexbox and the CSS grid are good at different things and should be used together, not as alternatives to one another.

For those of you who skip directly to the conclusion of articles (no worries, we do it too), here is a summary of the comparison:

Tags: , , ,
Posted in PHP Tutorials | Comments Off on CSS Grid VS Flexbox: A Practical Comparison

15 Interesting JavaScript and CSS Libraries for March 2017

Monday, March 6th, 2017

interesting-libraries-march-2017

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.


Propeller

Propeller

Propeller is a CSS components framework based on Bootstrap and Google’s Material Design language. It includes 25 components made with responsiveness in mind and featuring the typical Material Design animations. The project can be downloaded as a theme for Bootstrap, a full framework, or as stand alone components.


baguettebox

BaguetteBox

BaguetteBox is a pure JavaScript library for creating responsive lightbox galleries. It is very lightweight, mobile-ready, easy to use and customize, and utilizes CSS3 transitions for buttery-smooth image transitions.

We recently used this library in the making of our freebie pack of 4 Bootstrap Gallery Templates, and we can say we enjoyed working with BaguetteBox a lot.


Whitestorm

Whitestorm

Framework for developing 3D web apps and games using the Three.js engine. It provides straightforward wrappers for many common Three.js tasks, making it easier to set up an environment, create objects, add physics, and more. There is an official boilerplate project to get you started, as well as a tool for integration with React.


animatelo

Animatelo

Animatelo is a port of the extremely popular Animate.css library that replaces the CSS transitions with Web Animations API clones. All of the original Animate.css effects are recreated, but the API is now based on JavaScript methods instead of CSS classes. The library is lightweight and jQuery independent, but may require a polyfill on older browsers.


FuseBox

FuseBox

FuseBox is a bundle loader for JavaScript and CSS with optional add-ons for TypeScript, Sass, and more. It is created with simplicity and performance in mind, providing a viable alternative to webpack. To get you started there are quick boilerplate projects for Angular 2 + TypeScript, React + Babel, Vue.js, Electron, and others.


Yargs

Yargs

Yargs is a framework for building full-featured command line applications with Node.js. It allows you to easily configure commands, parse multiple –arguments, and setup shortcuts. It even generates help menus automatically.


WebGradients

WebGradients

A large collection of beautiful color gradients that can be easily applied to any HTML page. The project’s website allows you to quickly glance over the available gradients, see them in full screen, and one-click copy them as a CSS property.


Sticky-Kit

Sticky-Kit

Sticky-kit is a jQuery plugin that allows you to attach elements to a certain area on the page, making them stick to it’s boundaries. This way you can have a sidebar that is always visible and scrolls with the rest of the page, but can be contained within its parent container.


ScrollDir

ScrollDir

Super-lightweight, no-dependencies JavaScript library for monitoring scroll direction and movements. ScrollDir watches the movement of the scrollbar and toggles an up/down data-attribute on an element of your choice. It ignores small scroll movements, creating a smooth, non-jittery experience.


Svgo

Svgo

Node.js tool for optimizing SVG files, stripping them from various unnecessary information such as editor metadata, comments, hidden elements, and other attributes that don’t affect the rendered vector. SVGO has a plugin-based architecture, so you can freely choose what to remove and what to leave in.


Store.js

Store.js

Store.js is a cross-browser solution for advanced local storage. Recently, a version 2 was released, refreshing many of the features and adding extra functionality, such as array/object operations and improved expiration options.

In the previous issue of our monthly web dev resources list, we featured a similar library called localForage. It provides many of the same features as Store.js, but has a more localStorage-like syntax. Make sure to check it out as well.


Snarkdown

Snarkdown

Snarkdown is a super simple Markdown parser written in JavaScript. Admittedly, it’s not the most complicated or full-featured parser, but it’s probably the easiest to implement. Snarkdown is only 1kb in size and has only a single method, making it perfect for quick projects where a full parser would be overkill.


Unfetch

Unfetch

The Fetch API is a modern rework of the XMLHttpRequest interface, giving developers a much better way to handle asynchronous requests. Although it’s support now covers most modern browsers, the fetch() method is still unavailable in IE.

This brings us to Unfetch – a reliable polyfill in under 500 bytes.


Scrollanim

Scrollanim

Vanilla JavaScript library for on-scroll animations. Scrollanim offers lots of customization options, separate HTML and JavaScript APIs, and over 50 smooth animation effects thanks to the built-in Animate.css dependency.


Neurojs

Neurojs

JavaScript framework for experimenting with deep learning in the browser, featuring a full-stack neural network that can be trained via reinforcement-learning. The project showcases a cool Demo app where self-driving cars learn to navigate in a 2D environment.

Tags: , , ,
Posted in PHP Tutorials | Comments Off on 15 Interesting JavaScript and CSS Libraries for March 2017

Freebie: 4 Bootstrap Gallery Templates

Monday, February 20th, 2017

freebie-4-bootstrap-gallery-templates

In this post we would like to share with you 4 awesome image gallery templates for Bootstrap 3. Just like all our freebies, these templates are completely free to use (no attribution required), fully responsive, and super easy to implement – just copy and paste!

The Templates

The four templates use the Bootstrap 3 grid for their layouts. The HTML is fully compliant with the framework and follows the recommended practices. For styling we’ve used good ol’ CSS, while making sure to keep it self contained so it won’t mess up the rest of your styles.

Each template has unique CSS-only hover effects, as well as Lightbox functionality thanks to the baguetteBox.js plugin. There are many other Lightbox libraries out there but we chose that one because of the cool name (although it having no dependencies and being super easy to use were taking into account as well).

The BaguetteBox Plugin In Action

The BaguetteBox Plugin In Action

How to use

To use any of the templates from the demo, follow these simple steps:

  1. Grab the zip archive from the Download button near the top of the page and extract it.
  2. There are separate folders for each template + a folder of placeholder images (courtesy to Unsplash). Decide which template you want and grab it’s HTML from the .tz-gallery element in the index.html file.
  3. Paste the HTML into your project. Make sure you have Bootstrap 3 on that page.
  4. The styles are located in separate CSS files for each design. Link to the CSS file or copy its contents and add them to your styles.
  5. For the Lightbox effect add the baguetteBox CSS and JS, and initialize it in a script tag – baguetteBox.run('.tz-gallery');.
Gallery Template With Fluid Layout

Gallery Template With Fluid Layout

Free for Commercial Use

You have all rights to customize and use these templates in both personal and commercial projects. All our freebies are 100% royalty free, no attribution required (our license page). Enjoy!

Tags: , , ,
Posted in PHP Tutorials | Comments Off on Freebie: 4 Bootstrap Gallery Templates

Building Responsive Emails With MJML

Monday, February 13th, 2017

responsive-emails-with-mjml

Making HTML emails is just like building websites. The only difference is that layouts have to be constructed using <table>, CSS styles have to be written inline, and you have to support clients so out of date, they use Microsoft Word for rendering. So yeah, just like making websites, only infinitely worse.

One way to make email development easier is to use a framework which will take care of most of the above-mention issues. In this tutorial we will show you how to use the excellent MJML framework to make your own unique email templates.

Disclaimer: This tutorial contains images of delicious food. Read at your own risk!

1. What is MJML?

MJML provides a simple XML-like language that can be compiled to email-ready HTML. This way we don’t have to manually code entire layouts out of tables and legacy in-line styles.

MJML on the left, Email-ready HTML on the right

MJML on the left, Email-ready HTML on the right

The framework offers a rich set of standardized components with various customization options. By constructing our template out of MJML components, we make sure that we won’t use any non-email-proof CSS properties or HTML tags.

2. The Design

For a tasty example we will be making a simple pizza-themed newsletter. The finished MJML template, as well as a compiled HTML version can be downloaded from the Download button near the top of the page.

Our Pizza Newsletter

Our Pizza Newsletter

The layout consists of four major sections:

  1. Header
  2. Introduction
  3. Responsive list of popular products
  4. Footer with social buttons

For the sake of this tutorial we will fill the email with static dummy data. In real scenarios you want to have a template and some sort of system to generate newsletters every time you want to send one.

3. Installation

The easiest way to get started with MJML is using the framework’s CLI. To install it you will need to have Node.js on your machine, preferably v6.6.0 and above (we are using v6.9.5).

node -v
v6.9.5

Once you have that covered, open up a terminal window and install MJML globally, providing access to the mjml command.

npm install -g mjml
mjml --version
3.2.0

If you are using Atom or Sublime Text, there are also various helpful plugins that you can install if you want.

4. Working with MJML Documents

MJML is written in .mjml files. Create a new directory and add a template.mjml file. This is the only file we will be working on. It will contain all our markup and styles. Since we are making an email template, any external dependencies (mainly images) have to be included via CDN.

To compile .mjml files to .html, you need to open a terminal in the working directory and run one of the following commands:

# Compile template.mjml into output.html
mjml template.mjml -o output.html

# Watch template.mjml and auto-compile on every change.
mjml -w template.mjml -o index.html

Just like in HTML, our MJML document needs a head and a body

<mjml>
  <mj-head>
    <mj-attributes>
      <mj-all font-family="sans-serif" font-size="16px" color="#626262" />
      <mj-button background-color="#F45E43" color="#fff" font-size="14px" />
    </mj-attributes>
    <mj-style>
      .heading {
        padding-top: 15px;
        text-align: center;
        font-style: italic;
        font-size: 18px;
        font-family: "serif";
      }
    </mj-style>
  </mj-head>
  <mj-body>
    <mj-container background-color="#eee">

    <!-- Content goes here. -->

    </mj-container>
  </mj-body>
</mjml>

In the mj-head we’ve defined some default font styles to all MJML components, as well as styles for all our buttons. We’ve also added regular CSS, which on compilation will be in-lined by the framework. If you’ve never worked with HTML emails before try to avoid writing custom CSS styles, as many properties do not work correctly.

The mj-body will hold all our visible content. We’ve started with a container and given it a background color.

5. Header

MJML layouts are made out of sections (rows) and columns. For out header we will need two sections (two rows), each with one column in them. The first will have the newlsetter title, the other one will show a big pizza image.

The Header in Gmail Desktop (left) and the Android Gmail App (right)

The Header, Gmail Desktop (left) and Gmail Android App (right)

<!-- Header Text -->
<mj-section background-color="#fff">
  <mj-column>

    <mj-text  
      align="center"
      font-style="italic"
      font-size="32px"
      font-family="serif"
      padding-top="40px"
      padding-bottom="40px">The Pizza Times</mj-text>

  </mj-column>
</mj-section>
<!-- Pizza Image -->
<mj-section 
  background-url="http://demo.tutorialzine.com/2017/02/images/header-image.jpg"
  background-size="cover"
  background-repeat="no-repeat">

  <mj-column>

    <!-- Spacer component, used to give height to the background image. -->
    <mj-spacer height="300px" />

  </mj-column>
</mj-section>

As you can see, styles in MJML are described via specific attributes which are very similar to regular CSS. To see what properties are supported by each component go to the MJML documentation.

6. Intro Section

The second part of out template holds a heading, couple of paragraphs, an image link, and a call-to-action button.

The Intro Section, Gmail Desktop (left) and Gmail Android App (right)

The Intro Section, Gmail Desktop (left) and Gmail Android App (right)

<mj-section background-color="#fff">
  <mj-column width="450">

    <mj-text>
      <p class="heading">Hello Friends!<p></mj-text>

    <mj-text>
     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin rutrum enim eget magna efficitur, eu semper augue semper. Aliquam erat volutpat.</mj-text>

    <!-- The Href attributes turns our image into a link. -->
    <mj-image 
     src="http://demo.tutorialzine.com/2017/02/images/map.jpg" 
     border-radius="3" 
     href="#"/>

    <mj-text>
     Proin rutrum enim eget magna efficitur, eu semper augue semper. Aliquam erat volutpat.</mj-text>

    <mj-button 
     padding-bottom="25" 
     href="#">Make Reservation</mj-button>

  </mj-column>
</mj-section>

Mj-text components can contain any HTML text tags. We’ve used this to create the “Hello Friends” heading, by applying the .heading class we defined earlier in the <mj-head>.

Also in the <mj-head>, we defined default styles for our buttons, and as you can see, our call-to-action is now colored, even though it doesn’t have the background-color attribute.

7. Popular Products

This section contains a responsive layout of images and text. Clients that support responsiveness (e.g Gmail), will have a stacked layout on small screens, and a 2-column layout on bigger screens.

The Popular Products section, Gmail Desktop

The Popular Products Section, Gmail Desktop

MJML is mobile-first, so any email client that does not support media-queries, will always show the stacked layout.

The Popular Products section, Gmail Android App

The Popular Products Section, Gmail Android App

<mj-section 
  background-color="#fafafa" 
  padding="0 10px 10px">
  <mj-column>

    <mj-image 
      src="http://demo.tutorialzine.com/2017/02/images/pizza.jpg" 
      padding-left="10px" 
      padding-right="10px"/>

    <mj-image 
      src="http://demo.tutorialzine.com/2017/02/images/salad.jpg" 
      padding-left="10px" 
      padding-right="10px"/>

  </mj-column>   
  <mj-column>

    <mj-image 
      src="http://demo.tutorialzine.com/2017/02/images/cake.jpg" 
      padding-left="10px" 
      padding-right="10px"/>

    <mj-text 
      align="center" 
      font-size="14"
      padding-top="15px"
      padding-bottom="10px">
      <p style="max-width: 400px">Try our selection of Oven-baked Pizza, Fresh Salads, and Homemade Cake.<p></mj-text>

    <mj-button  
      padding-top="0"
      padding-bottom="15"
      href="#">Order Now</mj-button>

  </mj-column>  
</mj-section>

Responsiveness in MJML is done by placing multiple columns in the same section. On big screens the columns will share the available space, and on mobile will move under each other.

8. Footer

In the footer we will implement the very useful <mj-social> component. It allows us to effortlessly set-up buttons for sharing in social networks.

The Footer, Gmail Desktop (top) and Gmail Android App (bottom)

The Footer, Gmail Desktop (top) and Gmail Android App (bottom)

<mj-section background-color="#fff">
  <mj-column>

    <mj-text 
      align="center"
      font-size="11">The Pizza Times</mj-text>

    <mj-social 
      display="facebook instagram twitter"
      font-size="0"
      icon-size="16px"
      padding="0"
      facebook-href="#"
      instagram-href="#"
      twitter-href="#"/>

  </mj-column>
</mj-section>

You can choose from a range of social networks, and then add redirection URLs to your respective accounts. There are many customization options available, which you can check out in the docs.

With this our newsletter template is complete!

Further reading

In this tutorial we tried to cover all the basics of building responsive emails with MJML. If you want to get more advanced with your HTML email templates, here are some links and resources we recommend:

Tags: , , ,
Posted in PHP Tutorials | Comments Off on Building Responsive Emails With MJML

15 Interesting JavaScript and CSS Libraries for February 2017

Monday, February 6th, 2017

interesting-libraries-february-2017

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.


LocalForage

LocalForage

Wrapper for indexedDB and WebSQL that improves the ability of web apps to store data locally for offline use. Writing and reading is done in a similar fashion to localStorage but many types of data can be saved instead of only strings. The library also provides a dual API, giving developers the choice to use either callbacks or promises.


MJML

MJML

Building responsive emails is still considered the most annoying of web tasks. The MJML framework is aiming to change that by providing simple markup syntax with various stylized components that can be compiled to email-friendly HTML. This way developers don’t have to deal with table layouts, legacy CSS, and in-line styling.


Nachos UI

Nachos UI

Components kit for React Native containing over 30 customizable UI elements. You can find form inputs, loading indicators, a gravatar interface, and much more. The project’s documentation makes it really easy to understand how to implement each component and all the options that come with it.


FitVids

FitVids

A jQuery solution for responsive embedded videos that stick to their original aspect ratio. The plugin is mainly targeted at Vimeo and YouTube videos but allows any custom player to be adapted as well. Really useful and easy to work with.


Bttn.css

Monaco Editor

The editor engine behind Microsoft’s Electron based Visual Studio Code. It has everything you’d expect out of a modern code editor – syntax highlighting for many languages, multiple cursors, keyboard shortcuts, code completion, etc. Just like VSCode, Monaco is open-sourced so it can be used to power any editor project you have in mind.


Rellax

Rellax

Rellax is a mobile-friendly, zero-dependencies parallax library. It is only 1kb in size (gzipped), and in those 1000 bytes contains all that is needed to set up a parallax background effect. The API is based on HTML attributes, so all you have to do is define different speeds for the various elements on the page.


Keen UI

Keen UI

A collection of Material Design inspired Vue.js components. Keen UI is lightweight, Vue 2.1.4 compatible, and has lots of customization options. There are plenty of components and all of them look great.

In last month’s list we shared a similar framework called Vuetify. If you like developing with Vue.js, make sure to check that one out as well.


Muuri

Muuri

Muuri is a JavaScript library for creating awesome interactive grid layouts. It works by grabbing any number of rectangular tiles and placing them on a responsive grid, ordering them in the most space-economic way. These tiles can then be dragged around, sorted, and filtered, every action causing beautiful animated auto-reordering.


Tilt.js

Tilt.js

Tilt.js can take any DOM element and make it “float” in 3D space, allowing it to tilt in all directions when hovered. Options like amount of glare and additional effects can be set via HTML data-attributes or using the provided JavaScript methods. There are separate jQuery and vanilla JS versions.


Accesible Offcanvas

Offcanvas

Really easy to use jQuery plugin for creating off-canvas interfaces such as hamburger navigation menus. It has everything you expect out of a drawer: can be placed on any side of the screen, has smooth built-in CSS animation effects, and can be closed by pressing the Esc key or clicking on the page.


Notyf

Notyf

Super lightweight vanilla JavaScript library for displaying in-page notifications. Although there are many similar libraries, we wanted to share this one with you because of it’s super-clean API, stylish design, and subtle animations.


React Navigation

React Navigation

React Native components library containing different navigators suitable for iOS and Android apps. Right now it includes tabs, drawers, and stack (new screen opens on top of old one), and all three interfaces have different designs depending on which OS is used.


Ungrid

Ungrid

The worlds simplest responsive grid system, Ungrid is only 97 bytes and is composed of just 4 cleverly arranged CSS rules. Although it seems like an experimental project, Ungrid is actually quite flexible and can be used in live projects.


Multi.js

Multi.js

Multi.js offers a user-friendly alternative to the default browser-specific select inputs. The widget takes a select element with the multiple attribute and transforms it into a Bootstrap-inspired interface containing a search bar and scrollable picker. The library can be used with native JavaScript selectors or with jQuery.


Sugar

Sugar

Modular library for working with native JavaScript objects, extending their prototypes, and allowing developers to apply various utility functions directly onto JS variables. Sugar’s methods serve all kinds of purposes, ranging from basic maths to date formatting and type checking.

Tags: , , ,
Posted in PHP Tutorials | Comments Off on 15 Interesting JavaScript and CSS Libraries for February 2017

Free PHP Rating Script: Let your visitors give a star rating to stuff on your web page

Wednesday, February 1st, 2017

A new script has been added to the Free PHP Rating Scripts page. It allows visitors to your website to give a star rating to any item displayed there (such as pictures, videos, links, articles, or other content).

Tags: ,
Posted in Uncategorized | Comments Off on Free PHP Rating Script: Let your visitors give a star rating to stuff on your web page