Posts Tagged ‘php’

20 Excellent Resources for Learning Kotlin

Wednesday, May 24th, 2017

20-kotlin-resources

Кotlin is a modern programming language that runs on the Java Virtual Machine. It has an elegant syntax and is interoperable with all existing Java libraries. In the 2017 Google I/O, the Android team announced that Kotlin will become an official programming language for the Android platform. This puts Kotlin in position to become one of the top programming languages of the future.

To help you get started with your Kotlin journey, we’ve curated a list of some of the best Kotlin learning resources available right now. We haven’t included any paid courses or books, everything on the list is 100% free.


The Kotlin Website

The official website for the project is a very good place to start your Kotlin education. In the reference section you can find in-depth documentation that covers all the main concepts and features of the language. The tutorials section has a variety of practical step-by-step guides on setting up a working environment and working with the compiler.

There is also the Kotlin editor, a browser app that let’s you try out the language. It is loaded with many examples including the Koans course – by far the best way to get familiar with the syntax.

Keddit: Learn Kotlin while developing an Android App

An excellent 11-part series by Juan Ignacio Saravia in which he puts Kotlin into action and builds a Reddit clone app. The tutorials cover a vast number of topics ranging from setting up the workspace to using APIs and even unit testing. The code is available on GitHub.

Antonio Leiva’s Blog

Antoni Leiva’s blog is dedicated to all things Kotlin. It is updated weekly(ish) with high-quality tutorials and articles in which more advanced Kotlin developers can learn about new libraries and find all kinds of practical techniques.

Android Announces Support for Kotlin

The official Google blog post that explains the reasons behind the exciting announcement and why Kotlin deserves a place in the Android ecosystem. The article then goes on to give a brief preview of some of the awesome syntax improvements that Kotlin brings.

Design Patterns implemented in Kotlin

Dariusz Baciński has created a useful GitHub repo containing common design patterns implemented in Kotlin. There are similar projects written in several languages including Java, Swift, JavaScript, and PHP, so if you are coming from one of these programming background you can use them as a reference point.

Learn X in Y minutes

A quick cheatsheet with some of the most important features and syntax quirks that will help you write better Kotlin code. There are examples on working with classes, loops, and lists, as well as implementations of classic programming problems such as generating a Fibonacci sequence.

The Kotlin Blog

The official blog for Kotlin by its authors at JetBrains. Here you can find all Kotlin related news and updates, as well as all kinds of tutorials, tips, and other useful articles.

Get Started with Kotlin on Android

A helpful article from the Google Developers blog that explains how to setup Android Studio for Kotlin, how to convert .java files to .kt files, and how to incorporate the new language into an existing Android project. There are also some code comparisons on the same Android APIs used with both Kotlin and Java.

Android Testing With Kotlin

Great article that shows us how to write and run tests for Android apps using Kotlin. The author does a great job of explaining what different types of tests are available, when to use them, and how to make sure we are testing properly. Another good tutorial on this topic can be found here.


Introduction to Kotlin

A talk from Google I/O 2017 dedicated to introducing Kotlin to people for the first time and giving them an idea of how it can improve their workflow. It covers many of the basics and showcases some cool Kotlin tips.

Life is Great and Everything Will Be Ok, Kotlin is Here

The second Kotlin talk from Google I/O 2017. This one covers more advanced topics like design patterns, best practices, and other common principles. It also sheds some light on what it is like to use Kotlin in production and the challenges of adopting a young language in the workplace.

Peter Sommerhoff’s Kotlin Tutorials

Here is a free Kotlin course for complete beginners that includes all the basics from variables to conditionals to loops and functions. It then goes on to more advanced topics like object-orientation in Kotlin and functional programming like lambda expressions.

Better Android Development with Kotlin & Gradle

This talk from 2016 consists of a brief overview of the language’s features followed by a real world example where you’ll learn how Kotlin fits in with the existing tools in a typical Android workflow.

Better Android Development with Kotlin & Gradle

A very good 8-minute tutorial that quickly goes over the most important Kotlin features, such as the shortened variable declarations, lambdas, extension function, and more.

Android Development with Kotlin — Jake Wharton

Introduction to Kotlin that explains how the new language will improve the Android ecosystem and shows us a number of cool ways we can use the smart Kotlin syntax to our advantage.


From Java To Kotlin

Useful cheatsheet containing short snippets of code that will help you quickly look up the Kotlin alternatives to common Java operators, functions, and declarations.

Kotlin Educational Plugin

A plugin for IntelliJ IDEs that allows you to take the Koans course in a local offline environment.

Kotlin on GitHub

Kotlin has been open-source for more than 5 years and there is a GitHub repo containing the entire history of the project. If you want to support the language there are multiple ways you can contribute, be it directly or by working on the docs.

Kotlin Android Template

Template Android project that makes it super easy to setup a stable Kotlin workspace and quickly bootstrap your apps.

Awesome Kotlin

An extensive list of Kotlin resources containing all sorts of useful links, books, libraries, frameworks, and videos. The list is very well organized, with a stylized version also available at kotlin.link.

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

Getting Started With The JavaScript Web Animation API

Tuesday, May 16th, 2017

js-animations

Adding animations to web interfaces makes pages and apps feel more responsive and interactive. A side menu that smoothly slides out of view provides a much better user experience then a menu that just disappears when you close it.

So far creating web animations was done either via CSS transitions, CSS keyframes, or an external library such as Animate.css or Velocity. Thanks to a new native JavaScript API, we are now able to freely animate any HTML element without ever having to leave our .js file.

Creating Animations

To showcase the awesomeness of the new API, let’s build a super simple example, once the old-fashioned CSS way, then with JavaScript Web Animations.

The editor below contains two HTML divs that when clicked on move to the right and then change their color. The square is animated via CSS @keyframes, and the circle via the Web Animations API.

(Play with our code editor on Tutorialzine.com)

The @keyframes animation should be familiar to most developers so let’s look at that first.

The CSS Approach

Our CSS animation is defined in a @keyframes block that represents a timeline of all the transitions. Once we have our choreography defined, we can map it to a selector via the animation property and it’s options.

.animate {
    animation-name: move-and-change-color;   
    animation-duration: 0.4s;
    animation-fill-mode: forwards;
}

@keyframes move-and-change-color {
    0% {
        transform: translateX(0);
    }

    80% {
        transform: translateX(100px);
        background-color: #2196F3;
    }

    100% {
        transform: translateX(100px);
        background-color: #EF5350;
    }
}

We want the animation to start on user interaction so we will also have to create an on-click event listener that adds a CSS class to the desired element:

var square = document.getElementById('square');
    
square.addEventListener('click', function() {
    square.className += " animate";
});

Although it works pretty well, the CSS approach seems rather non-intuitive as we define what happens in the stylesheets, but actually start it in the JavaScript. We also have very limited control over the animation once it has been invoked. Both these problems can be solved by switching to the Web Animation API.

The JavaScript Approach

We can describe our JavaScript animation using almost the exact same transitions we used in the CSS example:

var moveAndChangeColor = [
    { 
        transform: 'translateX(0)',
        background: '#2196F3'    // blue
    },
    { 
        offset: 0.8,
        transform: 'translateX(100px)', 
        background: '#2196F3'    // blue
    },
    {
        transform: 'translateX(100px)',
        background: '#EF5350'    // red
    }
];

Each object in the array represents a state of the animation. The states are evenly distributed in time (3 states – 0%, 50%, 100%) unless we change the timing using the offset option, as we’ve done with the middle state.

After we’ve defined our animation array, we can invoke it using the animate() method. It takes as a second argument an object with the same options as the CSS animation property, although with slightly different names (e.g. animation-fill-mode is fill, animation-iteration-count is iteration, etc).

var circle = document.getElementById('circle');
  
circle.addEventListener('click', function() {
    circle.animate(moveAndChangeColor, {
        duration: 400,
        fill: 'forwards'
    });
});

As you can see, the JavaScript approach is much more organized with the animation stored in a variable and the animate() method used for invoking it whenever we need to.

Controlling Animations

The Web Animation API also makes it possible to easily control the playback of an animation in a number of ways. The animate() method returns an Animation object which we can save in a variable and use to refer to that animation later on.

var animation = elem.animate(transitions, options);

The interface provides us with the following methods:

Below is a tiny demo with a loading indicator that loops infinitely. We’ve setup buttons for the different events so that you can try them out:

(Play with our code editor on Tutorialzine.com)

Properties and Events Listeners

The Animation object returned from animate() holds several useful properties that give us access to options like the current time, the playback rate, and others. Although some are read-only, most of the properties can be used as setters and getters.

You can view the JS code in the editor below to get a sense of how they work. For the full list of properties visit MDN.

(Play with our code editor on Tutorialzine.com)

In addition to that, the Web Animation API provides us with two useful event handlers for when the animation has finished or has been canceled:

spinnerAnimation.addEventListener('finish', function() {
    // Animation has completed or .finish() has been called.
    doSomething();
});

spinnerAnimation.addEventListener('cancel', function() {
    // Animation has been canceled.    
    doSomething();
});

Support and Performance

Most of the Web Animation features are freely available in Chrome and Firefox, with Edge and Safari implementations in the working (caniuse). There is also a well maintained open-source polyfill which can be used while waiting for full browser coverage.

When it comes to performance, there shouldn’t be any difference compared to regular CSS transitions, as browsers use the same engine for both. If you stick to animating only properties that don’t cause redraws, such as transform and opacity, animations should keep a steady 60fps rate.

Conclusion

The Web Animation API gives developers an awesome new way to create and control web animations using nothing but pure JavaScript. For animations that are invoked on user interaction or other dynamic events, this is great news since the whole animation can be done in the controller code, without having to jump to a CSS file for the actual transitions.

This article covered most of the features of the new API, but if you want to learn more here are a couple of excellent resources we highly recommend:

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

5 Beautiful Image Effects With CSS Shapes and Filters

Tuesday, May 9th, 2017

5-beautiful-image-effects-with-css

Today we’ve prepared for you five background images showcasing the power of modern CSS. They can be used as desktop wallpapers, eye-catching landing pages, and even as printed posters. In the article below we’ll also go over some of the key CSS techniques, so that you can customize them to your liking or make your own ones from scratch.

The Designs

A Polyscape (poly = many, scape = scenery) is an image that contains multiple pictures mixed into one, creating very pleasing surrealistic visuals. Usually such design are made in Photoshop or other image editing software, but thanks to the ever growing arsenal of CSS properties, awesome polyscapes can now be created using nothing but simple web technologies!

You can view the designs in a demo app we created. The full source code plus all the polyscapes exported into HD images can be downloaded as a .zip archive from the Download button near the top of this page.

The demo uses some experimental CSS properties which might not work in all browsers. For the full experience, it’s best to open it in Chrome.

Polyscape of a mountain with CSS shapes and filters

Polyscape of a mountain with CSS shapes and filters.

Making these polyscapes was very easy and we had a lot of fun in the process. For the backgrounds we used images from Unsplash. Everything else is done via various CSS shapes, transforms, and filters.

CSS Shapes

The designs use a variety of geometrical shapes made out of CSS. Here is how they are done:

Another interesting CSS shape we wanted to make is a square that is transparent inside but has an image as its border:

Borders can have images as background.

Tilted squares with transparent background and image border.

It turns out there is a CSS spec that does exactly that – it’s called border-image and takes as parameters the path to an image, the border size, and how to place the image.

background: transparent;
border: 25px solid transparent;
border-image: url(clouds.jpg) 25 stretch;

CSS Filters

Since we are adding images on top of an image background, in many cases we need to apply some filters to make the two views stand out. Most modern browsers freely support this feature under the filter property.

It allows us to shift the hue from one color to another, boost the contrast, make everything black-and-white, and others. Here is a list of all the available CSS filters:

We can combine as many filters as we like until we get the desired result:

filter: hue-rotate(60deg) contrast(200%) blur(2px);

Conclusion

We hope you’ve enjoyed our little CSS experiment. The demo and all of the code is 100% free, and you have all rights to use, share, and change the designs (our license).

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

15 Interesting JavaScript and CSS Libraries for May 2017

Tuesday, May 2nd, 2017

interesting-libraries-may-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.


Buefy

Buefy

Ligthweight UI framework for Vue.js built using the popular flexbox-based CSS library Bulma. It has all the components a typical web app needs inluding dynamic elements like modals, toasts, and notifications, enableing devs to quickly add any user interface to their existing Vue.js projects.


HR.js

HR.js

Zero-dependency library for programatically highlighting and replacing strings within the DOM. The HR.js API couldn’t be simpler – just use a CSS selector to target the parent HTML element holding the desired text, choose which words to highlight, set the background color, and you’re done!


react1

React VR

React VR is a framework for the creation of VR applications that run in your web browser. It pairs modern APIs like WebGL and WebVR with the declarative power of React, producing experiences that can be consumed through a variety of devices.


Tippy.js

Tippy.js

Pure JavaScript library for animated tooltips. It provides a wide range of different on-hover effects and a ton of customization with over 20 options. Tippy.js is super ligthweight and has rather good browser compatibility, automatically falling back to regular title attributes when not supported.


Barba.js

Barba.js

Dependancy-free JavaScript library for creating smooth transtitions between the views of your single page apps. The logic is built around PJAX (push state AJAX) which checks all valid URLs, prevents their normal behavior and instead loads the new page via a XMLHttpRequest. Barba also makes sure the change in state is properly reflected in your app’s URL via the Push State API.


UIkit

UIkit

Excellent CSS and JavaScript front-end framework, including its own SVG icon font and dozens of components. UIkit is designed very well, both in looks and as a framework, with unified styles, easy to remember API, many customization options, and useful modifyer classes. The docmentation is also top-notch.


haul_

Haul

Haul is a command line tool for developing React Native apps. It can be used as a direct replacement of the React Native packager, providing better webpack support, improved error messages, and greatly reduced compilation times. Haul is well documented, customizable, and completely open-source.


AcrossTabs

AcrossTabs

JavaScript library for communicationg between cross-origin browser tabs, making it possible for one web page to open and close additional browser tabs. The parent tab has access to useful information about its children tabs, including unique ids and whether the child tab is still open or has been closed.


Stylelint

Stylelint

Stylelint is a modern CSS linter that will help teams eforce unopinionated CSS standards in their stylesheets. The library is pretty powerful and can forbid or whitelist specific properties, catch errors, and recognize SCSS syntax. Stylelint is totaly cusotmizable, giving you the option to add new rules or opt-out of those that you don’t agree with.


Iconate

Iconate

Awesome vanilla JavaScript library that allows you to transform one icon to another on click, with a variety of smooth animations. Iconate works with all CSS icon fonts – just add an icon to your HTML and use the simple JavaScript API to choose what to transform it into and which of the 15+ animations to use.


React-Datasheet

React-Datasheet

React component that can be used for adding fully functional Excel-like datasheets to your apps. Table cells can be freely edited, group-selected, copied, pasted, deleted, and everything else you’d expect, with keyboard navigation also available. There are 3 useful examples on their GitHub – a basic table, spreasheet with formulas, and table with nested components.


Pure CSS

Pure CSS

Modular CSS framework with a minimal footprint. The entire library is just 3.8 kb minified and gzipped but this size can be further reduced by excluding the parts you don’t need. Modules include a base set of styles, a responsive grid, form components, buttons, tables, and menus.


Simple Icons

Simple Icons

Huge collection of free icons for popular social networks, apps, services, and other brands. Since all the icons are made with SVG they can be scaled to any size without fear of pixelation or smudges. Being SVG-based also makes them super lightweight – most are under 500 bytes, more detailed ones around 1 or 2 KB.


Chroma.js

Chroma.js

Tiny JavaScript library for working with colors. It offers a rich API with over 50 functions for manipulating colors, letting you swtich between color modes, change brightness and saturation, create gradient scales, and many other useful methods.


Weex

Weex

Weex is a framework for building cross-platform mobile apps, similar to Reat Native but for Vue.js. It allows you to write your app in HTML, CSS, and JavaScript, which then will be rendered in Java for Android and Swift for iOS. The framework has a number of built-in components, APIs, and other helpful utilites.

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

10 Machine Learning Examples in JavaScript

Tuesday, April 25th, 2017

10-machine-learning-resources-1

Machine learning libraries are becoming faster and more accessible with each passing year, showing no signs of slowing down. While traditionally Python has been the go-to language for machine learning, nowadays neural networks can run in any language, including JavaScript!

The web ecosystem has made a lot of progress in recent times and although JavaScript and Node.js are still less performant than Python and Java, they are now powerful enough to handle many machine learning problems. Web languages also have the advantage of being super accessible – all you need to run a JavaScript ML project is your web browser.

Most JavaScript machine learning libraries are fairly new and still in development, but they do exist and are ready for you to try them. In this article we will look at some of these libraries, as well as a number of cool AI web app examples to get you started.


Brain

1. Brain

Brain is a library that lets you easily create neural networks and then train them based on input/output data. Since training takes up a lot of resources, it is preferred to run the library in a Node.js environment, although a CDN browser version can also be loaded directly onto a web page. There is a tiny demo on their website that can be trained to recognize color contrast.


Deep playground

Deep playground

Educational web app that lets you play around with neural networks and explore their different components. It has a nice UI that allows you to control the input data, number of neurons, which algorithm to use, and various other metrics that will be reflected on the end result. There is also a lot to learn from the app behind the scenes – the code is open-source and uses a custom machine learning library that is written in TypeScript and well documented.


FlappyLearning

FlappyLearning

FlappyLearning is a JavaScript project that in roughly 800 lines of unminifed code manages to create a machine learning library and implement it in a fun demo that learns to play Flappy Bird like a virtuoso. The AI technique used in this library is called Neuroevolution and applies algorithms inspired by nervous systems found in nature, dynamically learning from each iteration’s success or failure. The demo is super easy to run – just open index.html in the browser.


Synaptic

Synaptic

Probably the most actively maintained project on this list, Synaptic is a Node.js and browser library that is architecture-agnostic, allowing developers to build any type of neural network they want. It has a few built-in architectures, making it possible to quickly test and compare different machine learning algorithms. It’s also features a well written introduction to neural networks, a number of practical demos, and many other great tutorials demystifying how machine learning works.


Land Lines

Land Lines

Land Lines is an interesting Chrome Web experiment that finds satellite images of Earth, similar to doodles made by the user. The app makes no server calls: it works entirely in the browser and thanks to clever usage of machine learning and WebGL has great performance even on mobile devices. You can check out the source code on GitHub or read the full case study here.


ConvNetJS

ConvNetJS

Although it is no longer actively maintained, ConvNetJS is one of the most advanced deep learning libraries for JavaScript. Originally developed in Stanford University, ConvNetJS became quite popular on GitHub, resulting in many community driven features and tutorials. It works directly in the browser, supports multiple learning techniques, and is rather low-level, making it suitable for people with bigger experience in neural networks.


Thing Translator

Thing Translator

Thing Translator is a web experiment that allows your phone to recognize real-life objects and name them in different languages. The app is built entirely on web technologies and utilizes two machine learning APIs by Google – Cloud Vision for image recognition and Translate API for natural language translations.


Neurojs

Neurojs

Framework for building AI systems based on reinforcement learning. Sadly the open-source project doesn’t have a proper documentation but one of the demos, a self-driving car experiment, has a great description of the different parts that make up a neural network. The library is in pure JavaScript and made using modern tools like webpack and babel.


Machine_learning

Machine_learning

Another library that allows us to set up and train neural networks using only JavaScript. It is super easy to install both in Node.js and in the client side, and has a very clean API that will be comfortable for developers of all skill levels. The library provides a lot of examples that implement popular algorithms, helping you understand core machine learning principals.


DeepForge

DeepForge

DeepForge is a user-friendly development environment for working with deep learning. It allows you to to design neural networks using а simple graphical interface, supports training models on remote machines, and has built in version control. The project runs in the browser and is based on Node.js and MongoDB, making the installation process very familiar to most web devs.


Machine Learning in Javascript

Bonus: Machine Learning in Javascript

An excellent series of blog posts by Burak Kanber that goes over some of the machine learning fundamentals. The tutorials are well written, clear, and targeted specifically towards JavaScript developers. A great resource if you want to understand machine learning more in depth.

Conclusion

Although the JavaScript machine learning ecosystem is not fully developed yet, we recommend using the resources on this list to make your first steps in ML and get a feel for the core techniques. As the experiments in the article show, there are tons of fun stuff you can make using only the browser and some familiar JavaScript code.

Tags: , , ,
Posted in PHP Tutorials | Comments Off on 10 Machine Learning Examples in JavaScript

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 | Comments Off on Handle Mouse And Touch Input With The Pointer Events API

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 | Comments Off on Learn Webpack in 15 Minutes

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 | Comments Off on 15 Interesting JavaScript and CSS Libraries for April 2017

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