Posts Tagged “coding”

Tracking Internal Marketing Campaigns With Google Analytics

Tracking Internal Marketing Campaigns With Google Analytics

Editor’s Note: This article is targeted at readers experienced in using Google Analytics. If you’re new to Analytics, the following guide might be challenging.

Many websites use internal advertising in the form of banners or personalized product recommendations to bring additional products and services to the attention of visitors and to increase conversions and leads. read more

Read more »

Building A Simple AI Chatbot With Web Speech API And Node.js

Building A Simple AI Chatbot With Web Speech API And Node.js

Using voice commands has become pretty ubiquitous nowadays, as more mobile phone users use voice assistants such as Siri and Cortana, and as devices such as Amazon Echo and Google Home1 have been invading our living rooms. These systems are built with speech recognition software that allows their users to issue voice commands2. Now, our web browsers will become familiar with to Web Speech API, which allows users to integrate voice data in web apps.

With the current state of web apps, we can rely on various UI elements to interact with users. With the Web Speech API, we can develop rich web applications with natural user interactions and minimal visual interface, using voice commands. This enables countless use cases for richer web applications. Moreover, the API can make web apps accessible, helping people3 with physical or cognitive disabilities or injuries. The future web will be more conversational and accessible!

Enhancing User Experience Link

Web Speech API enables websites and web apps not only to speak to you, but to listen, too. Take a look at just some great examples of how it can be used to enhance the user experience. Read more →4

In this tutorial, we will use the API to create an artificial intelligence (AI) voice chat interface in the browser. The app will listen to the user’s voice and reply with a synthetic voice. Because the Web Speech API is still experimental, the app works only in supported browsers5. The features used for this article, both speech recognition and speech synthesis, are currently only in the Chromium-based browsers, including Chrome 25+ and Opera 27+, while Firefox, Edge and Safari support only speech synthesis at the moment.

Browser compatibility6
(View large version7)

This video shows the demo in Chrome, and this is what we are going to build in this tutorial!

[embedded content]
A simple AI chat bot demo with Web Speech API

To build the web app, we’re going to take three major steps:

  1. Use the Web Speech API’s SpeechRecognition interface to listen to the user’s voice.
  2. Send the user’s message to a commercial natural-language-processing API as a text string.
  3. Once API.AI returns the response text back, use the SpeechSynthesis interface to give it a synthetic voice.
The app flow8

The entire source code9 used for this tutorial is on GitHub.

Prerequisites Link

This tutorial relies on Node.js. You’ll need to be comfortable with JavaScript and have a basic understanding of Node.js.

Make sure Node.js10 is installed on your machine, and then we’ll get started!

Setting Up Your Node.js Application Link

First, let’s set up a web app framework with Node.js. Create your app directory, and set up your app’s structure like this:

.
├── index.js
├── public
│ ├── css
│ │ └── style.css
│ └── js
│ └── script.js
└── views
 └── index.html

Then, run this command to initialize your Node.js app:

$ npm init -f

The -f accepts the default setting, or else you can configure the app manually without the flag. Also, this will generate a package.json file that contains the basic info for your app.

Now, install all of the dependencies needed to build this app:

$ npm install express socket.io apiai --save

With the --save flag added, your package.json file will be automatically updated with the dependencies.

We are going to use Express11, a Node.js web application server framework, to run the server locally. To enable real-time bidirectional communication between the server and the browser, we’ll use Socket.IO12. Also, we’ll install the natural language processing service tool, API.AI13 in order to build an AI chatbot that can have an artificial conversation.

Socket.IO is a library that enables us to use WebSocket easily with Node.js. By establishing a socket connection between the client and server, our chat messages will be passed back and forth between the browser and our server, as soon as text data is returned by the Web Speech API (the voice message) or by API.AI API (the “AI” message).

Now, let’s create an index.js file and instantiate Express and listen to the server:

const express = require('express'); const app = express(); app.use(express.static(__dirname + '/views')); // html app.use(express.static(__dirname + '/public')); // js, css, images const server = app.listen(5000); app.get('/', (req, res) => { res.sendFile('index.html'); }); read more

Read more »

Do you want to Create Custom Inputs With Vue.js ?

Do you want to Create Custom Inputs With Vue.js ?

Component-based libraries or frameworks such as Vue have given us the wonderful ability to create reusable components to be spread throughout their respective application, ensuring that they are consistent, and (hopefully) simplifying how they are used.

In particular, form inputs tend to have plenty of complexity that you’d want to hide in a component, such as custom designs1, labels, validation, help messages, and making sure each of these pieces are in the correct order so that they render correctly.

On top of that though, Vue has a built-in directive called v-model that simulates 2-way binding by binding a value and capturing input events. If you’re going to build a custom input component, then you’ll definitely want to support the v-model directive.

Sadly, when I looked around for examples of custom inputs in Vue for radio buttons or checkboxes, they either didn’t take v-model into consideration at all, or they failed to implement it correctly. There is some decent documentation for custom text inputs2, but since it doesn’t explain customizing radios or checkboxes, we’ll discuss that here.

This tutorial aims to help you…

  1. Understand how v-model works on native inputs, focusing primarily on radios and checkboxes
  2. Understand how v-model works on custom components by default
  3. Learn how to create custom checkboxes and radios that emulate how v-model works on them natively

Quick note before we get started: ES2015+ code will be used throughout the code examples. I’ll also be favoring the Single File Component3 syntax over using Vue.component or new Vue.

Further Reading on SmashingMag: Link

How Does v-model Work Normally? Link

The official Vue documentation8 is actually pretty good on this topic, but there are a few minor blind spots. In any case, we’ll be trying to cover it pretty thoroughly here.

In essence, v-model is just a shorthand directive that gives us 2-way data binding, and the code it is shorthand for depends on what type of input it is being used on.

Text Boxes Link

<input v-model="message" placeholder="edit me"> <p>Message: {{ message }}</p> <!-- OR --> <p>message:</p> <p style="white-space: pre-line">{{ message }}</p> <textarea v-model="message" placeholder="add multiple lines"></textarea>

When using a text input (including types such as email, number, etc.) or textarea, v-model="varName" is equivalent to :value="varName" @input="e => varName = e.target.value". This means that the value of the input is set to varName after each update to the input varName is updated to the value of the input. A normal select element will act like this too, though a multiple select will be different.

Radio Buttons Link

So, what about radio buttons?

<input type="radio" value="One" v-model="picked"> <input type="radio" value="Two" v-model="picked"> <span>Picked: {{ picked }}</span>

read more

Read more »

Progressively Enhancing CSS Layout: From Floats To Flexbox To Grid

Progressively Enhancing CSS Layout: From Floats To Flexbox To Grid

Earlier this year, support for CSS grid layout1 landed in most major desktop browsers. Naturally, the specification is one of the hot topics at meet-ups and conferences. After having some conversations about grid and progressive enhancement, I believe that there’s a good amount of uncertainty about using it. I heard some quite interesting questions and statements, which I want to address in this post.

Statements And Questions I’ve Heard In The Last Few Weeks Link

  • “When can I start using CSS grid layout?”
  • “Too bad that it’ll take some more years before we can use grid in production.”
  • “Do I need Modernizr in order to make websites with CSS grid layout?”
  • “If I wanted to use grid today, I’d have to build two to three versions of my website.”
  • “Progressive enhancement sounds great in theory, but I don’t think it’s possible to implement in real projects.”
  • “How much does progressive enhancement cost?”

These are all good questions, and not all of them are easy to answer, but I’m happy to share my approach. The CSS grid layout module is one of the most exciting developments since responsive design. We should try to get the best out of it as soon as possible, if it makes sense for us and our projects.

Demo: Progressively Enhanced Layout Link

Before going into detail and expounding my thoughts on the questions and statements above, I want to present a little demo42 I’ve made.

Disclaimer: It would be best to open the demo on a device with a large screen. You won’t see anything of significance on a smartphone.

Progressively enhanced CSS Layout, with Flexbox and CSS Grid.3
The home page of an example website, with an adjustable slider to switch between different layout techniques.

When you open the demo42, you’ll find yourself on the home page of a website with a very basic layout. You can adjust the slider in the top left to enhance the experience. The layout switches from being very basic to being a float-based layout to being a flexbox layout and, finally, to being one that uses grid.

It’s not the most beautiful or complex design, but it’s good enough to demonstrate which shapes a website can take based on a browser’s capabilities.

This demo page is built with CSS grid layout and doesn’t use any prefixed properties or polyfills. It’s accessible and usable for users in Internet Explorer (IE) 8, Opera Mini in Extreme mode, UC Browser and, of course, the most popular modern browsers. You can perfectly use CSS grid layout today if you don’t expect exactly the same appearance in every single browser, which isn’t possible to achieve nowadays anyway. I’m well aware that this decision isn’t always up to us developers, but I believe that our clients are willing to accept those differences if they understand the benefits (future-proof design, better accessibility and better performance). On top of that, I believe that our clients and users have — thanks to responsive design — already learned that websites don’t look the same in every device and browser.

In the following sections, I’m going to show you how I built parts of the demo and why some things just work out of the box.

Quick side note: I had to add a few lines of JavaScript and CSS (an HTML5 shim) in order to make the page work in IE 8. I couldn’t resist, because IE 8+ just sounds more impressive than IE 9+.

CSS Grid Layout And Progressive Enhancement Link

Let’s take a deeper look at how I built the “four levels of enhancement” component in the center of the page.

HTML Link

I started off by putting all items into a section in a logical order. The first item in the section is the heading, followed by four subsections. Assuming that they represent separate blog posts, I wrapped each of them in an article tag. Each article consists of a heading (h3) and a linked image. I used the picture element here because I want to serve users with a different image if the viewport is wide enough. Here, we already have the first example of good ol’ progressive enhancement in action. If the browser doesn’t understand picture and source, it will still show the img, which is also a child of the picture element.

<section>
 <h2>Four levels of enhancement</h2>
 <article><h3>No Positioning</h3><a href="#"> <picture> <source srcset="320_480.jpg" media="(min-width: 600px)"> <img src="480_320.jpg" alt="image description"> </picture></a>
 </article>
</section>

Float Enhancements Link

A component of the demo page built with float
All items in the “four levels of enhancement” component, floated left

On larger screens, this component works best if all items are laid out next to each other. In order to achieve that for browsers that don’t understand flexbox or grid, I float them, give them a size and some margin, and clear the floating after the last floated item.

article { float: left; width: 24.25%; } article:not(:last-child) { margin-right: 1%; } section:after { clear: both; content: ""; display: table; } read more

Read more »

Introducing The Website Speed Test Image Analysis Tool

Introducing The Website Speed Test Image Analysis Tool

Web developers spend their days writing hypertext, but, byte for byte, most of the web is composed of images1. It is hard to overstate the effect that images have on the average web page’s performance; faster websites have broader reach2 and a higher impact3. The first and most important thing you can do to improve the performance of your website’s images is figure out how to measure them.

Enter Website Speed Test4, a free and drop-dead-simple tool that leverages our (Cloudinary’s) image smarts to let you measure, diagnose and (crucially) communicate about the image performance of any website. Better yet, it’s built on top of, and integrated in, Pat Meenan’s WebPagetest5. read more

Read more »

Building Pattern Libraries With Shadow DOM In Markdown

Building Pattern Libraries With Shadow DOM In Markdown

Some people hate writing documentation, and others just hate writing. I happen to love writing; otherwise, you wouldn’t be reading this. It helps that I love writing because, as a design consultant offering professional guidance, writing is a big part of what I do. But I hate, hate, hate word processors.

My typical workflow using a desktop word processor goes something like this:

  1. Select some text I want to copy to another part of the document.
  2. Note that the application has selected slightly more or less than I told it to.
  3. Try again.
  4. Give up and resolve to add the missing part (or remove the extra part) of my intended selection later.
  5. Copy and paste the selection.
  6. Note that the formatting of the pasted text is somehow different from the original.
  7. Try to find the styling preset that matches the original text.
  8. Try to apply the preset.
  9. Give up and apply the font family and size manually.
  10. Note that there is too much white space above the pasted text, and press “Backspace” to close the gap.
  11. Note that the text in question has elevated itself several lines at once, joined the heading text above it and adopted its styling.
  12. Ponder my mortality.

When writing technical web documentation (read: pattern libraries1), word processors are not just disobedient, but inappropriate. Ideally, I want a mode of writing that allows me to include the components I’m documenting inline, and this isn’t possible unless the documentation itself is made of HTML, CSS, and JavaScript. In this article, I’ll be sharing a method for easily including code demos in Markdown, with the help of shortcodes and shadow DOM encapsulation.

An M, a down-arrow plus a dective hidden in the dark symbolizing Markdown and Shadown Dom

CSS And Markdown Link

Say what you will about CSS, but it’s certainly a more consistent and reliable typesetting tool than any WYSIWYG editor or word processor on the market. Why? Because there’s no high-level black-box algorithm that tries to second-guess what styles you really intended to go where. Instead, it’s very explicit: You define which elements take which styles in which circumstances2, and it honors those rules.

The only trouble with CSS is that it requires you to write its counterpart, HTML. Even great lovers of HTML would likely concede that writing it manually is on the arduous side when you just want to produce prose content. This is where Markdown comes in. With its terse syntax and reduced feature set, it offers a mode of writing that is easy to learn but can still — once converted into HTML programmatically — harness CSS’ powerful and predictable typesetting features. There’s a reason why it has become the de facto format for static website generators and modern blogging platforms such as Ghost.

Where more complex, bespoke markup is required, most Markdown parsers will accept raw HTML in the input. However, the more one relies on complex markup, the less accessible one’s authoring system is to those who are less technical, or those short on time and patience. This is where shortcodes come in.

Shortcodes In Hugo Link

Hugo3 is a static site generator written in Go — a multi-purpose, compiled language developed at Google. Due to concurrency (and, no doubt, other low-level language features I don’t fully understand), Go makes Hugo a lightening-fast generator of static web content. This is one of the many reasons why Hugo has been chosen for the new version of Smashing Magazine.

Performance aside, it works in a similar fashion to the Ruby and Node.js4-based generators with which you may already be familiar: Markdown plus meta data (YAML or TOML) processed via templates. Sara Soueidan has written an excellent primer5 on Hugo’s core functionality.

For me, Hugo’s killer feature is its implementation of shortcodes6. Those coming from WordPress may already be familiar with the concept: a shortened syntax primarily used for including the complex embed codes of third-party services. For instance, WordPress includes a Vimeo shortcode that takes just the ID of the Vimeo video in question.

[vimeo 44633289]

The brackets signify that their content should be processed as a shortcode and expanded into the full HTML embed markup when the content is parsed.

Making use of Go template functions, Hugo provides an extremely simple API for creating custom shortcodes. For example, I have created a simple Codepen shortcode to include among my Markdown content:

Some Markdown content before the shortcode. Aliquam sodales rhoncus dui, sed congue velit semper ut. Class aptent taciti sociosqu ad litora torquent.

{{<codePen VpVNKW>}}

Some Markdown content after the shortcode. Nulla vel magna sit amet dui lobortis commodo vitae vel nulla sit amet ante hendrerit tempus.

Hugo automatically looks for a template named codePen.html in the shortcodes subfolder to parse the shortcode during compilation. My implementation looks like this:

{{ if .Site.Params.codePenUser }} <iframe height='300' scrolling='no' title="code demonstration with codePen" src='//codepen.io/{{ .Site.Params.codepenUser | lower }}/embed/{{ .Get 0 }}/?height=265&theme-id=dark&default-tab=result,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'> <div> <a href="//codepen.io/{{ .Site.Params.codePenUser | lower }}/pen/{{ .Get 0 }}">See the demo on codePen</a> </div> </iframe> {{ else }} <p class="site-error"><strong>Site error:</strong> The <code>codePenUser</code> param has not been set in <code>config.toml</code></p> {{ end }} read more

Read more »