Tag Archiv: Tutorial
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
How to use
To use any of the templates from the demo, follow these simple steps:
- Grab the zip archive from the Download button near the top of the page and extract it.
- 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.
- Paste the HTML into your project. Make sure you have Bootstrap 3 on that page.
- 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.
- 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
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!
A free pack of responsive Bootstrap 3 image gallery templates with smooth CSS on-hover effects and Lightbox overlays.
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
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
The layout consists of four major sections:
- Header
- Introduction
- Responsive list of popular products
- 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, 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)
<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
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
<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)
<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:
- The official MJML docs and starting guide – here
- Live editor where you can experiment and try out different ideas – here
- Example templates – here
- Litmus PutsMail, a free tool for sending test emails – here
- Foundation for Emails, another popular framework for HTML emails – here
We tried the MJML framework, we liked it, and decided to share the results. Read the article to see how easy it has become to write HTML newsletters.
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.
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.
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.
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.
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.
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 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.
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 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 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.
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.
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 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.
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 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.
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.
February's list is packed with awesome web dev resources, including UI frameworks for React Native and Vue.js, a new solution for offline storage, and the world's smallest responsive grid!
A curated list of some of our favorite open-source PHP libraries and frameworks from the last couple of months.
This week we have for you a collection of high-quality PHP libraries that have caught our eye in the last couple of months. We’ve tried our best to include projects that are active, well documented, and will have a realistic shot at finding a place in your developer’s workbelt.
If we’ve haven’t included your favorite new library, feel free to share it in the comments :)
A no-dependencies library that lets you send HTTP requests. It provides the needed methods for adding headers, accessing response data, handling forms, and everything else you may need, neatly packaged in a clean and easy to use API.
$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);
var_dump($request->status_code);
// int(200)
var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"
var_dump($request->body);
// string(26891) "[...]"
Rinvex Country is a PHP package that lets developers retrieve detailed information about the countries of the world. Using the over 50 methods you can get the area of Angola, the currency of Cyprus, the native name of Namibia or even the FIFA name of Finland. There is a ton of info available and the data sources are pretty reliable.
$egypt = country('eg');
$egypt->getCapital(); // Cairo
$egypt->getDemonym(); // Egyptian
$egypt->getTld(); // .eg
$egypt->getContinent(); // Africa
$egypt->getSubregion(); // Northern Africa
$egypt->getBorders(); // ["ISR","LBY","SDN"]
A PHP library for developing messenger bots. Works with most of the popular messaging platforms including Facebook Messenger, Slack, Telegram, WeChat, and others. There is also a helpful boilerplate Laravel project available here.
// create an instance
$botman = BotManFactory::create($config);
// give the bot something to listen for.
$botman->hears('hello', function (BotMan $bot) {
$bot->reply('Hello yourself.');
});
// start listening
$botman->listen();
If you are not familiar with the concept of messenger bots we suggest you check out our article Developer’s Introduction To Chatbots.
Laravel package for generating highly customizable charts out of datasets. The package works as a PHP wrapper for multiple built-in JavaScript chart libraries, allowing devs to create a wide variety of graphs, gauges and progressbars using only one tool.
$chart = Charts::create('line', 'highcharts')
->view('custom.line.chart.view')
->title('My nice chart')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(false);
Swap allows you to retrieve currency exchange rates from a number of services such as Fixer, Google, and Yahoo. Request responses can be easily cached and accessed later. The library is available in the form of a Laravel Package as well.
// Build Swap with Fixer.io
$swap = (new Builder())
->add('fixer')
->build();
// Get the latest EUR/USD rate
$rate = $swap->latest('EUR/USD');
// 1.129
$rate->getValue();
// Get the EUR/USD rate 15 days ago
$rate = $swap->historical('EUR/USD', (new \DateTime())->modify('-15 days'));
A collection of mathematical functions and algorithms ranging from simple algebra to finances, statistics, numerical analysis and others fields. The library is modular, has a straightforward API, and doesn’t require any external dependencies.
// Factors of an integer
$factors = Algebra::factors($n);
// Fibonacci sequence
$fib = Advanced::fibonacci($n);
// Combinations
$nCk = Combinatorics::combinations($n, $k);
// Likelihood ratios
$LL = Experiment::likelihoodRatio($a, $b, $c, $d);
PHPUnit is an advanced testing framework that enables teams to thoroughly test their code. Unit tests are written in standalone object-oriented classes with the help of many methods for handling assertions, dependencies, etc. A simple CLI is provided for running test and generating reports.
class StackTest extends TestCase
{
public function testPushAndPop()
{
$stack = [];
$this->assertEquals(0, count($stack));
array_push($stack, 'foo');
$this->assertEquals('foo', $stack[count($stack)-1]);
$this->assertEquals(1, count($stack));
$this->assertEquals('foo', array_pop($stack));
$this->assertEquals(0, count($stack));
}
}
A less popular testing framework we also wanted to share. Atoum offers a one-step installation precess and a relatively simple workflow, while still maintaining a ton of great features. It has a mock engine, expressive assertions, and a CLI that can execute multiple tests in parallel.
$this->given($testedInstance = new testedClass())
->and($testedClass[] = $firstValue = uniqid())
->then
->sizeof($testedInstance)->isEqualTo(1)
->string($testedClass[0])->isEqualTo($firstValue);
A PHP implementation of the Simple Regex Language – a verbose way of writing regular expressions. The library provides multiple methods that can be chained together, forming readable and easy to understand RegEx rules. The library has ports for JavaScript and Python as well.
$query = SRL::startsWith()
->anyOf(function (Builder $query) {
$query->digit()
->letter()
->oneOf('._%+-');
})->onceOrMore()
->literally('@')
->anyOf(function (Builder $query) {
$query->digit()
->letter()
->oneOf('.-');
})->onceOrMore()
->literally('.')
->letter()->atLeast(2)
->mustEnd()->caseInsensitive();
Stash makes it easy to speed up your code by caching the results of expensive functions or code. Certain actions, like database queries or calls to external APIs, take a lot of time to run but tend to have the same results over short periods of time. This makes it much more efficient to store the results and call them back up later.
$pool = $this->cachePool;
// Get a Stash object from the cache pool.
$item = $pool->getItem("/user/{$userId}/info");
// Get the data from it, if any happens to be there.
$userInfo = $item->get();
// Check to see if the cache missed, which could mean that it either
// didn't exist or was stale.
if($item->isMiss())
{
// Run the relatively expensive code.
$userInfo = loadUserInfoFromDatabase($userId);
// Set the new value in $item.
$item->set($userInfo);
// Store the expensive code so the next time it doesn't miss.
$pool->save($item)
}
A port of the popular Ruby library for testing HTTP interactions. PHP VCR records HTTP requests and stores them in “cassettes” which can be replayed later on. A set of testing utilities are also provided, making it possible to inspect and compare recordings in detail.
// After turning on, the VCR will intercept all requests
\VCR\VCR::turnOn();
// Record requests and responses in cassette file 'example'
\VCR\VCR::insertCassette('example');
// Following request will be recorded once and replayed in future test runs
$result = file_get_contents('http://example.com');
$this->assertNotEmpty($result);
// To stop recording requests, eject the cassette
\VCR\VCR::eject();
// Turn off VCR to stop intercepting requests
\VCR\VCR::turnOff();
This library allows you to easily configure an OAuth 2.0 server and set up all the authentication levels needed to protect your API. It is fully standards compliant and supports all the grants defined by OAuth protocol. The Laravel Passport module is built on top of the OAuth 2.0 Server.
// Setup the authorization server
$server = new \League\OAuth2\Server\AuthorizationServer(
$clientRepository,
$accessTokenRepository,
$scopeRepository,
$privateKey,
$publicKey
);
// Enable a grant on the server
$server->enableGrantType(
new \League\OAuth2\Server\Grant\ClientCredentialsGrant(),
new \DateInterval('PT1H') // access tokens will expire after 1 hour
);
An image manipulation library that tries to bring together all low level PHP image processing libraries under the same object-oriented API. This allows Imagine to be used for a wide variety of tasks such as drawing, resizing, cropping, filters, effects, metadata editing, and others.
$palette = new Imagine\Image\Palette\RGB();
$image = $imagine->create(new Box(400, 300), $palette->color('#000'));
$image->draw()
->ellipse(new Point(200, 150), new Box(300, 225), $image->palette()->color('fff'));
$image->save('/path/to/ellipse.png');
Extremely simple and easy to understand skeleton PHP application, providing only the most essential features every project needs. It does not strive to be a do-it-all framework like Laravel, but due to it’s simplicity MINI can be used for getting smaller apps up and running in no time.
// Working with the model
$songs = $this->model->getAllSongs();
$amount_of_songs = $this->model->getAmountOfSongs();
// Loading views
require APP . 'views/_templates/header.php';
require APP . 'views/songs/index.php';
require APP . 'views/_templates/footer.php';
The official PHP library for working with Amazon Web Services. The SDK makes it easy to connect AWS with any PHP project and access all the various available services. There is also a useful Laravel wrapper which can be found here.
// Instantiate an Amazon S3 client.
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-west-2'
]);
$s3->putObject([
'Bucket' => 'my-bucket',
'Key' => 'my-object',
'Body' => fopen('/path/to/file', 'r'),
'ACL' => 'public-read',
]);
Lightweight PHP library for working with URLs. With Purl you can compose complex paths attribute by attribute, extract data from URLs, manipulate queries, recognize URLs in strings, and much more.
$url = \Purl\Url::parse('http://jwage.com')
->set('scheme', 'https')
->set('port', '443')
->set('user', 'jwage')
->set('pass', 'password')
->set('path', 'about/me')
->set('query', 'param1=value1¶m2=value2');
echo $url->getUrl(); // https://jwage:password@jwage.com:443/about/me?param1=value1¶m2=value2
echo $url->publicSuffix; // com
echo $url->registerableDomain; // jwage.com
Documentation generator that uses a simple folder structure and Markdown files to create responsive documentation websites. Daux.io has automatic syntax highlighting, 4 theming options, Bootstrap HTML for easy customization, navigation with readable URLs, and many other goodies.
// Example configuration
{
"title": "DAUX.IO",
"tagline": "The Easiest Way To Document Your Project",
"author": "Justin Walsh",
"image": "app.png",
"html": {
"theme": "daux-blue",
"breadcrumbs": true,
"repo": "justinwalsh/daux.io",
"edit_on_github": "justinwalsh/daux.io/blob/master/docs",
"twitter": ["justin_walsh", "todaymade"],
"google_analytics": "UA-12653604-10",
"links": {
"Download": "https://github.com/justinwalsh/daux.io/archive/master.zip",
"GitHub Repo": "https://github.com/justinwalsh/daux.io",
"Made by Todaymade": "http://todaymade.com"
}
}
}
Dompdf is a PDF generator that takes regular HTML markup and converts it to .pdf files. It understands most CSS rules, which can be fed in-line or via an external stylesheet.
// reference the Dompdf namespace
use Dompdf\Dompdf;
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
$dompdf->stream();
Non-official library for accessing the Instagram API. It provides developers with an easy way to authenticate their app and get access to various Instagram data endpoints including images, users, likes, comments, and tags.
$api = new Instaphp\Instaphp([
'client_id' => 'your client id',
'client_secret' => 'your client secret',
'redirect_uri' => 'http://somehost.foo/callback.php',
'scope' => 'comments+likes'
]);
$popular = $api->Media->Popular(['count' => 10]);
if (empty($popular->error)) {
foreach ($popular->data as $item) {
printf('<img src="%s">', $item['images']['low_resolution']['url']);
}
}
Zero-dependencies library for building SQL queries using chainable methods. It supports most query types and works well with MySQL, Postgres, SQL Server, and other databases. There are also built-in escaping helpers for protecting against SQL injection.
$select = SelectQuery::make(
'id',
'username'
)
->from('users');
echo $select->sql();
// SELECT id, username FROM users
The JavaScript Web Notification API allows both desktop and mobile browsers to display notifications with custom content. Although it’s support used to be quite inconsistent, the API is now compatible with most modern browsers and we are already seeing it implemented in many websites and apps.
In this article we will show you the quickest way to set up browser notifications using the open-source Push.js library.
Project Setup
We want to build a simple demo app that asks for permission and then sends notification on button click. For the sake of simplicity we will work in a single index.html file with inline scripts. The full source is available on GitHub.
The first thing we need to do is include the library. Push.js can be installed via npm or a local file, but the easiest way to implement it is via CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/push.js/0.0.11/push.min.js"></script>
The Push.js library is not necessary for working with Web Notifications, but is offers a clean API which is much easier to work with compared to the native Notification API. Push.js will handle permissions, service workers, and cross-browser inconsistencies, so we don’t have to.
Requesting Permission
Users need to give permission before we can send them notifications. This is done through a built-in browser dialog which you’ve probably seen already:
Permission Request Dialog
Push.js automatically asks for permission when we try to send our first notification. However, in many cases we want to manually ask the users beforehand:
Push.Permission.request();
This will open the built-in browser dialog prompting users to accept or refuse to receive notifications. If permission has already been granted or denied, the above code will be ignored.
Creating A Notification
To display a notification we simply call the Push.create
method, which expects a title and an optional object holding all kinds of useful preferences and callbacks:
Push.create('Hi there!', {
body: 'This is a notification.',
icon: 'icon.png',
timeout: 8000, // Timeout before notification closes automatically.
vibrate: [100, 100, 100], // An array of vibration pulses for mobile devices.
onClick: function() {
// Callback for when the notification is clicked.
console.log(this);
}
});
You can see all the available options here.
In our demo we display a notification on button click, but user interaction isn’t required – new notifications can be created at any time, including when the tab isn’t active at the moment.
Browser Notification in Desktop Chrome
Make sure not to bother users too much. Send notification only when you want to update them on something important like a new text message or a new friend request.
Browser Compatibility
The Notification API is supported in most modern browsers. To see if your browser of choice supports it, try running our demo app. It should work without a problem in desktop Chrome, Firefox, and Safari, as well as Chrome for Android. The only popular client that’s missing from this list is iOS Safari, which doesn’t provide any form of web notifications.
Another important thing to note here is that in order for notifications to be shown in Android, the web app needs to be hosted over HTTPS.
Further Reading
Notifications are a relatively new addition to the browser world but we can expect to see more and more of them, especially as Progressive Web Apps become more popular. If you want to learn more about JavaScript notifications, here are some great resource that we recommend you check out :
- A blog post by the creator of Push.js, discussing why he created the project and his future plans for it – here.
- Push API – An awesome new API that allows users to receive notifications even when a web app isn’t open – here.
- What Makes a Good Notification? – A Google Developers article on how to make notifications better – here.
In this tutorial we show you a quick way to display native browser notifications in your web app.