How to Get Started With restdb.io and Create a Simple CMS

How to Get Started With restdb.io and Create a Simple CMS

This article was sponsored by restdb.io. Thank you for supporting the partners who make SitePoint possible.

Databases strike fear into the heart of the most experienced developers. Installation, updates, disk space provision, back-ups, efficient indexing, optimized queries, and scaling are problems most could do without. Larger organizations will employ a knowledgeable dev ops person who dedicates their life to the database discords. Yet the system inevitably fails the moment they go on vacation.

A more practical option is to outsource your database and that’s exactly the service restdb.io provides. They manage the tricky data storage shenanigans, leaving you to concentrate on more urgent development tasks.

restdb.io: the Basics

restdb.io is a plug and play cloud NoSQL database. It will be immediately familiar to anyone with MongoDB experience. The primary differences:

  • there’s no need to manage your installation, storage or backups
  • you can define a data structure schema in restdb.io
  • data fields can have relationships with other fields in other collections
  • there’s no need to define indexes
  • data can be queried and updated through a REST API authenticated by HTTP or Auth0/JWT tokens
  • queries and updates are sent and received in JSON format
  • there are tools to enter, view and export data in various formats
  • it supports some interesting bonus features such as codehooks, email, web form generation, websites, realtime messaging, and more.

A free account allows you to assess the service with no obligation. Paid plans offer additional storage space, query throughput, developer accounts and MongoDB integration.

In the following sections I’ll describe how to:

  1. configure a new database and enter data
  2. use that data to render a set web pages hosted on restdb.io, and
  3. use the API to provide a search facility for content editors.

Step 1: Create a New Database

After signing up with a Google, Facebook or email account, you can create a new empty database. This generates a new API endpoint URL at yourdbname.restdb.io:

create a new database

Step 2: Create a New Collection

A database contains one or more collections for storing data. These are analogous to SQL database tables. Collections contain “documents” which are analogous to SQL database records (table rows).

The restdb.io interface offers two modes:

  1. Standard mode shows the available collections and allows you to insert and modify data.
  2. Developer mode allows you to create and configure collections.

enter developer mode

Enter Developer Mode (top-right of screen) and click the Add Collection button.

create a new collection

A collection requires a unique name (I’ve used “content”) and an optional description and icon. Hit Save to return to your database overview. The “content” collection will appear in the list along with several other non-editable system collections.

Alternatively, data can be imported from Excel, CSV or JSON files to create a collection by hitting Import in the standard view.

Step 3: Define Fields

Staying in Developer Mode, click the “content” collection and choose the Fields tab. Click Add Fields to add and configure new fields which classify the data in the collection.

create fields

Each collection document will sore data about a single page in the database-driven website. I’ve added five fields:

  • slug – a text field for the page path URL
  • title – a text field for the page title
  • body – a special markdown text field for the page content
  • image – a special image field which permits any number of uploaded images (which are also stored on the restdb.io system)
  • published – boolean value which must be true for pages to be publicly visible.

Step 4: Add Documents

Documents can be added to a collection in either standard or developer mode (or via the API). Create a few documents with typical page content:

create documents

The slug should be empty for the home page.

Step 5: Create a Database-Driven Website (Optional)

restdb.io provides an interesting feature which can create and host a database-driven website using data documents in a collection.

The site is hosted at www-yourdbname.restdb.io but you can point any domain at the pages. For instructions, click Settings from the Database list or at the bottom of the left-hand panel then click the Webhosting tab.

To create the website, Pages must be configured in Developer Mode which define templates to view the content. Templates contain a code snippet which sets:

  1. the context – a query which locates the correct document in a collection, and
  2. the HTML – a structure which uses handlebars template syntax to insert content into appropriate elements.

Click Add Page to create a page. Name it the special name /:slug – this means the template will apply to any URL other than the home page (which does not have a slug). Hit Save and return to the page list, then click the /:slug entry to edit.

Switch to the Settings tab and ensure text/html is entered as the Content Type and Publish is checked before hitting Update:

create page

Now switch to the Code for “/:slug” tab. Enter the context code at the top of the editor:

{{#context}}
{
  "docs": {
    "collection": "content",
    "query": {
      "slug": "{{pathparams.slug}}",
      "published": true
    }
  }
}
{{/context}}

This defines a query so the template can access a specific document from our content collection. In this case, we’re fetching the published document which matches the slug passed on the URL.

All restdb.io queries return an array of objects. If no document is returned, the docs array will be empty so we can add code to return that the page is not available immediately below the context:

<!doctype html>
{{#unless docs.[0]}}
  <html>
  <body>
    <h1>Page not available</h1>
    <p>Sorry, this page cannot be viewed. Please return later.</p>
  </body>
  </html>
{{/unless}}

Below this, we can code the template which slots the title, body and image fields into appropriate HTML elements:

{{#with docs.[0]}}
  <html>
  <head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <style>
      body {
        font-family: sans-serif;
        font-size: 100%;
        color: #333;
        background-color: #fff;
        max-width: 40em;
        padding: 0 2em;
        margin: 1em auto;
      }
    </style>
  </head>
  <body>
    <header>
      {{#each image}}
        <img src="https://sitepoint-fbbf.restdb.io/media/{{this}}" alt="image" />
      {{/each}}

      <h1>{{title}}</h1>
    </header>
    <main>
      {{markdown body}}

      <p><a href="/">Return to the home page...</a></p>
    </main>
  </body>
  </html>
{{/with}}

Note our markdown body field must be rendered with a markdown handler.

Save the code with Ctrl|Cmd + S or by returning to the Settings tab and hitting Update.

The /:slug page template will apply to all our content collection — except for the home page, because that does not have a slug! To render the home page, create a New Page with the name home with identical settings and content. You may want to tweak the template for home-page-specific content.

Once saved, you can access your site from https://www-yourdbname.restdb.io/. I’ve created a very simple three-page site at https://www-sitepoint-fbbf.restdb.io/.

For more information about restdb.io page hosting, refer to:

Step 6: API Queries

Creating a site to display your data may be useful, but you’ll eventually want to build an application which queries and manipulates information.

restdb.io’s REST API provides endpoints controlled via HTTP:

  • HTTP GET requests retrieve data from a collection
  • HTTP POST requests create new documents in a collection
  • HTTP PUT requests update documents in a collection
  • HTTP PATCH requests update one or more properties in a document in a collection
  • HTTP DELETE requests delete documents from a collection

There are a number of APIs for handling uploaded media files, database meta data and mail but the one you’ll use most often is for collections. The API URL is:

https://yourdbname.restdb.io/rest/collection-name/

The URL for my “content” collection is therefore:

https://sitepoint-fbbf.restdb.io/rest/content/

Queries are passed to this URL as a JSON-encoded querystring parameter named q, e.g. fetch all published articles in the collection:

https://sitepoint-fbbf.restdb.io/rest/content/q={"published": true}

However, this query will fail without an API key passed in the x-apikey HTTP header. A full-access API key is provided by default but it’s advisable to create keys which are limited to specific actions. From the database Settings, API tab:

create a new database

Click Add New to create a new key. The one I created here is limited to GET (query) requests on the content collection only. You should create a similarly restricted key if you will be using client-side JavaScript Ajax code since the string will be visible in the code.

It’s now possible to build a standalone JavaScript query handler (ES5 has been used to ensure cross-browser compatibility without a pre-compile step!):

// restdb.io query handler
var restDB = (function() {

  // configure for your own DB
  var 
    api = 'https://sitepoint-fbbf.restdb.io/rest/',
    APIkey = '597dd2c7a63f5e835a5df8c4';

  // query the database
  function query(url, callback) {

    var timeout, xhr = new XMLHttpRequest();

    // set URL and headers
    xhr.open('GET', api + url);
    xhr.setRequestHeader('x-apikey', APIkey);
    xhr.setRequestHeader('content-type', 'application/json');
    xhr.setRequestHeader('cache-control', 'no-cache');

    // response handler
    xhr.onreadystatechange = function() {
      if (xhr.readyState !== 4) return;
      var err = (xhr.status !== 200), data = null;
      clearTimeout(timeout);
      if (!err) {
        try {
          data = JSON.parse(xhr.response);
        }
        catch(e) {
          err = true;
          data = xhr.response || null;
        }
      }
      callback(err, data);
    };

    // timeout
    timeout = setTimeout(function() {
      xhr.abort();
      callback(true, null);
    }, 10000);

    // start call
    xhr.send();
  }

  // public query method
  return {
    query: query
  };

})();

This code passes queries to the restdb.io API endpoint and sets the appropriate HTTP headers including x-apikey for the API key. It times out if the response takes longer than ten seconds. A callback function is passed an error and any returned data as a native object. For example:

// run a query
restDB.query(
  '/content?q={"published":true}',
  function(err, data) {
    // success!
    if (!err) console.log(data);
  }
);

The console will output an array of documents from the content collection, e.g.

[
  {
    _id: "1111111111111111",
    slug: "",
    title: "Home page",
    body: "page content...",
    image: [],
    published: true
  },
  {
    _id: "22222222222222222",
    slug: "page-two",
    title: "Page Two",
    body: "page content...",
    image: [],
    published: true
  },
  {
    _id: "33333333333333333",
    slug: "page-three",
    title: "Another page",
    body: "page content...",
    image: [],
    published: true
  }
]

The API can be called from any language which can make an HTTP request. restdb.io provides examples for cURL, jQuery $.ajax, JavaScript XMLHttpRequest, NodeJS, Python, PHP, Java, C#, Objective-C and Swift.

I’ve created a simple example at Codepen.io which allows you to search for strings in the title and body fields and displays the results:

See the Pen restdb.io query by SitePoint (@SitePoint) on CodePen.

It passes the following query:

{ "$or": [
  { "title": {"$regex": "searchstring"} }, 
  { "body":  {"$regex": "searchstring"} }
]}

where searchstring is the search text entered by the user.

An additional h querystring parameter limits the returned fields to just the slug, title and published flag:

{
  "$fields": {
    "slug": 1,
    "title": 1,
    "published": 1
  }
}

Further information:

Step 7: Build Your Own CMS

A few steps were required to create a database-driven website and a simple search facility. You could edit pages directly using restdb.io’s user interface but it would be possible to build a bespoke CMS to manipulate the content. It would require:

  1. A new restdb.io API key (or change the existing one) to have appropriate GET, POST, PUT, PATCH and DELETE access to the content collection.
  2. A user interface to browse or search for pages (the one above could be a good starting point).
  3. A process to start a new page or GET existing content and place it in an editable form.
  4. Processes to add, update or delete pages using the appropriate HTTP methods.

The editing system should run on a restricted device or behind a login to ensure only authenticated users can access. Take care not to reveal your restdb.io API key if using client-side code!

Further information:

Try restdb.io Today!

This article uses restdb.io to build a rudimentary CMS, but the service is suitable for any project which requires data storage. The REST API can be accessed from any language or framework which makes it ideal for applications with multiple interfaces, e.g. a web and native mobile view.

restdb.io provides a practical alternative to managing your own database software installation. It’s simple to use, fast, powerful, highly scalable and considerably less expensive than hiring a database expert! Your application hosting costs will also reduce since all data is securely stored and backed-up on the restdb.io servers.

Finally, restdb.io makes you more productive. You can concentrate on the main application because data storage no longer causes concerns for you and your team.

Start building your restdb.io database today and let us know how you get on!

Continue reading %How to Get Started With restdb.io and Create a Simple CMS%


Source: Sitepoint

Frame by Frame Animation Tutorial with CSS and JavaScript

Frame by frame animation with HTML, CSS and JavaScript

Imagine your designer asked you to implement a beautiful frame by frame animation for the awesome project you’ve been working on. As the front-end dev on the project, not only is it up to you to come up with a working animation, but also to deliver a silky smooth, performant and maintainable frame by frame animation that works great across different browsers, both on desktop and mobile.

This tutorial shows you the various ways you can create this type of animation with HTML, CSS, and JavaScript, while improving on each iteration to achieve the best result for your project.

What Is a Frame by Frame Animation?

According to this definition by Adobe, a frame by frame animation:

… changes the contents of the Stage in every frame. It is best suited to complex animation in which an image changes in every frame instead of simply moving across the Stage.

In other words, the subject of the animation is represented in a set of images. Each image in the set occupies an animation frame, and the rate of change with which each frame replaces the next produces the illusion of motion in the image.

I will demonstrate the whole workflow as you’ll be working on this great blinking eye animation from Zeiss website.

This is the set of images you’ll be using to build the animation frames:

Blinking eye sprite for frame by frame animation

And here’s the final result:

Blinking eye frame by frame animation

For this tutorial, I’ve chosen to use SVG images because they are great at scaling with different screen sizes for responsive web design. However, if for whatever reason you don’t want to use SVG graphics, you can create web animations with PNG, JPEG, and GIF image formats or use HTML5 Canvas. I will share my thoughts on these alternatives at the end of the article.

For simplicity’s sake, in this tutorial you’ll be using the jQuery library and have Autoprefixer up and running, therefore the code will be free of browser-specific CSS prefixes.

Now, let’s do some coding!

1 — Frame by Frame Animation by Changing the Image’s Source

The first option is straightforward enough, and that’s one reason why I like it.

In your HTML document, create an img element, which acts as container for the images, one at a time, as each animation frame is replaced by the next:

[code language=”html”]
<img class=”eye-animation”
src=”https//helpx.adobe.com/images/Eye-1.svg”
alt=”blinking eye animation”/>
[/code]

The CSS:

[code language=”css”]
.eye-animation {
width: 300px;
}
[/code]

The next step is to replace the existing image with the next one over a period of time dynamically, so as to create the illusion of movement.

You could do it with setTimeout but it’s better to use requestAnimationFrame. Doing so has some advantages from the point of view of performance. For example:

  • The quality of other animations on the screen won’t be affected
  • The browser will stop the animation if users navigate to another tab.

Here’s the jQuery code:

[code language=”js”]
const $element = $(‘.eye-animation’);
const imagePath = ‘/images’;
const totalFrames = 18;
const animationDuration = 1300;
const timePerFrame = animationDuration / totalFrames;
let timeWhenLastUpdate;
let timeFromLastUpdate;
let frameNumber = 1;

function step(startTime) {
if (!timeWhenLastUpdate) timeWhenLastUpdate = startTime;

timeFromLastUpdate = startTime – timeWhenLastUpdate;

if (timeFromLastUpdate > timePerFrame) {
$element.attr(‘src’, imagePath + `/Eye-${frameNumber}.svg`);
timeWhenLastUpdate = startTime;

if (frameNumber >= totalFrames) {
frameNumber = 1;
} else {
frameNumber = frameNumber + 1;
}
}

requestAnimationFrame(step);
}
[/code]

When the page loads, you call requestAnimationFrame for the first time and pass the step function to it, together with the animation’s startTime parameter built into the requestAnimationFrame function.

At each step the code checks how much time has passed from the last image source update and, if it’s longer than the required time per frame, then it refreshes the image.

Because you’re building an infinite animation, the code above checks if it’s got to the last frame and if so, it resets the frameNumber to 1; if not, it increases the frameNumber by 1.

Images should have the same name structure made of an increasing number series and the same location (e.g., images/Eye-1.svg, images/Eye-2.svg, images/Eye-3.svg, etc.) so that the code can easily iterate through them.

Finally, call requestAnimationFrame again to continue the whole process.

It looks good. However, if you try this you’ll see it won’t work because when the animation starts, only the first image gets loaded. The reason for this is that the browser knows nothing about the images you want to display until the code updates the image element’s src attribute in the middle of the animation loop. For a smooth animation, you need to preload the images before the loop starts.

There are different ways you can do this. Here’s the one I like best. It consists in appending hidden divs and setting their background-image property to point to the required images.

The jQuery code:

[code language=”js”]
$(document).ready(() => {
for (var i = 1; i < totalFrames + 1; i++) {
$(‘body’).append(`<div id=”preload-image-${i}” style=”background-image: url(‘${imagePath}/Eye-${i}.svg’);”></div>`);
}
});
[/code]

Here’s the full working demo on CodePen:

See the Pen Frame by frame-animation-1-source by SitePoint (@SitePoint) on CodePen.

Below I’ve listed some pros and cons to this approach.

Cons:

  • With HTTP v1.1, having to load multiple images can significantly increase page load time on the first visit
  • The animation can be janky on mobile devices. That’s because the browser has to perform a repaint each time the image element’s src attribute is updated (please check out Paul Lewis’ blog post for the details).

Pros:

  • Declarative — the code just iterates through the set of images
  • The image is fixed in one place — no jumping back and forth is visible (you’ll see why this is important below).

2 — Frame by Frame Animation by Changing the Image’s Opacity

To avoid browser repaints, you could change the images’ opacity instead of changing their source.

You could render all the images with opacity: 0 at page load and then set opacity: 1 for exactly when you want to show that frame.

That would improve rendering performance, but you’ll still have to preload all the images up front (which could be tricky if you have other images on the page as well and don’t want to wait for all of them to load). Also, because of multiple images, you’ll still have a longer first-time page load duration.

Here’s the full code:

You can avoid HTML code duplication by leveraging the capabilities of template engines such as Pug, Twig, React, Angular etc., or by just appending the divs using JavaScript as you did in the previous example.

3 — Frame by Frame Animation by Changing the Sprite’s Position

The usual workaround to prevent having to download multiple images consists in using an image sprite.

So, let’s do that.

Continue reading %Frame by Frame Animation Tutorial with CSS and JavaScript%


Source: Sitepoint

How Nostalgia in Web Design Captivates Users (with examples)

Vintage photography

Nostalgia makes users feel warm inside. Suzanne Scacca explains the user psychology behind this, and how we can utilize the effects of nostalgia in web design on users for higher conversions and engagement (with examples).

———

Right now, more than ever before, we’re seeing all sorts of nostalgic throwbacks causing us to reminisce about the good ol’ days! We’re seeing an endless supply of remakes, reboots and long-awaited sequels like Spider-Man and Ghostbusters; Bruno Mars topping the music charts with songs that sound eerily similar to classic hits by Kool & the Gang; women wearing chokers and high-waisted pants.

And this isn’t a new phenomenon either.

Every generation daydreams about how things were way back when, and what’s changed since.

It’s true, nostalgia is a very powerful emotion. It can even make us feel happy and at the same time, and in design/marketing, we can use nostalgia to captivate users…then convert them.

What the Research Says About Nostalgia

Nostalgia stirs up very strong feelings, so there’s something to be said about user psychology and why we continue to see retro throwbacks time and time again. After all, the goal in marketing is to create content that taps into our audience’s emotional core and establishes a much deeper connection with them far beyond a superficial “Buy 1, Get 1 Free” offer.

Nostalgia achieves that well.

So. Jumping on the retro bandwagon: is it really worth it when “comebacks” tend to have such a short-term expiration?

Yes.

Studies suggest that not only are nostalgic marketing angles captivating to audiences, simply for the reminiscent feelings accosted with them, but retro visual aesthetics can boost these effects even further, and that’s where design comes into it. Let’s take a closer look at what exactly happens when we feel nostalgic.

Nostalgia in web design makes visitors feel more connected

Dr. Filippo Cordaro, a researcher of nostalgia from the University of Cologne, found similarities between an individual reminiscing about the past and the level of social connectivity they felt. He explains:

“On a basic level, recalling these positive memories simply puts us in a more positive mood. On a more complex level, recalling these experiences makes us feel a stronger sense of social connectedness with others.”

Positive feelings and nostalgia

It’s the latter half of this conclusion that’s most important for marketers and web designers to understand; that feeling of “connectedness” is what we should be striving for, and we can do this by telling stories through visual design and using imagery that visitors can relate to. While a superficial offer/discount might grab the user’s attention momentarily, digging deeper into the audience’s emotional core and establishing a more genuine, heartfelt connection is more effective overall.

In short: nostalgic hooks are more memorable because they’re based on experiences familiar to the visitor.

Real Examples (and what we can learn from them)

If you’re curious to see how you might use nostalgic hooks in visual design and communication, then check out what these brands have done and the effects they’ve had.

Danner

Overall, the vintage-style typography and classic insignia-style details compliment the (more modernized) minimal/flat approach to the layout, where the two styles come together to convey the vintage brand that is Danner’s boots. Danner’s was founded in 1932, so you could say that the visual aesthetic is a modern twist on a vintage brand that customers already know and love. You have to stay true to your roots (as they say), but you also have stay with the times. Danner’s Boots does both.

Also, as you may have noticed, brown/beige colors are quite common in vintage visual aesthetics. Color can also play a huge role in influencing how users feel.

Danner's Boots

Desires Tram

Desires Tram is another web design example where mixing somewhat minimalistic layouts with vintage details has worked well. What we can take away from this is that serif fonts can still be bold, and bitmap images don’t have to impact loading times too much if used sparingly. Overall, these design elements, the “mascot” character and the magical sounds strike a wonderful blend of creativity and nostalgia like something straight out of Harry Potter.

Robby Leonardi

Retro video games. Now we’re getting to closer to the heart, because this is more likely to be “your era”. I wouldn’t be surprised if developer Robby Leonardi’s interactive resume resonates with you more than the first two examples, because retro video games are more likely take you back to your childhood (well…it depends how old you are I suppose!).

Brown/beige/grunge/vintage styles are certainly captivating and may induce feelings of nostalgia from a visual perspective, but it’s not something that’s likely resonate with you from an emotional angle (not unless you’re into vintage things, which you may very well be).

Even those that didn’t play old-school Nintendo games will undoubtedly recognize the “game” as a Super Mario-style game, so this is a type of nostalgia that won’t be lost on many users. It definitely takes me back and ultimately gets me to stick around his website a little longer.

Robby Leonardi

St. Louis Browns Historical Society

St. Louis Browns Historical Society is a terrific example of a website that makes use of real life footage. The home video approach intentionally touches the heart, and the rest of the website continues with some of the visual details we’ve seen in the other examples: grungey visuals and serif fonts combined with flat elements and sans-serif fonts, a perfectly executed combination of vintage and modern that lets retro designs work on the web today.

Continue reading %How Nostalgia in Web Design Captivates Users (with examples)%


Source: Sitepoint

Securing Your Website with HTTPS Is More Important than Ever

Securing Your Website with HTTPS Is More Important than Ever

There’s been a huge movement to make the web secure in recent days and this is mostly due to the consequences of not securing your site.

If you have a website, or you’re thinking about deploying your site soon, you need to consider making it work with HTTPS.

Now, before we go over the issues of not having a secure site (spoiler alert: it’s a big deal even if you ignore the security concerns), let’s go over how many sites are using HTTPS as of mid-2017.

According to Firefox’s telemetry data, ~60% of page views are being loaded over HTTPS:

Securing Your Website with HTTPS Is More Important than Ever

That shows about a +20% adoption rate in 18 months, which is very impressive considering that accounts for all page views on the internet, not just page views on top sites.

Chrome’s telemetry data is in the same ballpark as Firefox:

Securing Your Website with HTTPS Is More Important than Ever

Why Is Everyone Scrambling to Secure Their Site?

The reality is, hosting an insecure site just isn’t good enough…

  • Google ranks insecure pages (HTTP) worse than secure pages (HTTPS)
  • Your visitor’s browsing activity and data isn’t encrypted or protected
  • Chrome and Firefox are ​adding scary visual cues to punish insecure sites. That means, even non-technical folk are now receiving in your face warnings that your site is dangerous to view…

Securing Your Website with HTTPS Is More Important than Ever

It started with the secure lock icon, but that’s old news. Browser vendors have been doing that for years.

Recently, they have been rolling out more aggressive cues, and it’s going to continue to get worse and worse for insecure sites as time goes on.

A few current and upcoming visual cues in Chrome and Firefox:

Securing Your Website with HTTPS Is More Important than Ever

Firefox is already showing the visual cues on the right, and Chrome is about to transition to using a non-red “Not secure” label in October 2017, with the red version coming eventually.

Even a non-technical user can see that it’s bad and dangerous.

These are in your face warnings that your site is not secure. I don’t know about you, but there’s no way in heck that I would consider putting sensitive information into an insecure form.

Insecure Sites Let Anyone Who Is Watching View Your Browsing Habits

I don’t even like browsing anonymously on insecure sites because that means all of your browsing habits can be spied on by your ISP (Internet Service Provider) or anyone watching. With net neutrality constantly being attacked, this is a big deal and ultimately affects everyone in the world.

As website owners, we can do our best to secure the web one site at a time by simply securing our sites over HTTPS. It’s not a war that we can’t win either. We are winning (world wide HTTPS coverage is over 50%)!

Continue reading %Securing Your Website with HTTPS Is More Important than Ever%


Source: Sitepoint

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.

Tracking Internal Marketing Campaigns With Google Analytics

Naturally, the performance and effectiveness of internal marketing campaigns should be assessed, too, as this is one of the most powerful instruments for generating more leads, more conversions and more revenue on your website. In many cases, web analysts use Google Analytics’ UTM campaign parameters to track internal advertising.

The post Tracking Internal Marketing Campaigns With Google Analytics appeared first on Smashing Magazine.


Source: Smashing Magazine

JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback

In the previous tutorial of the Anime.js series, you learned about different kinds of parameters that control how different target elements should be animated. You also learned how to use function parameters to gradually change the delay or duration of the elements. 

In this tutorial we will go a step further and learn how to specify the property values themselves using regular numbers, function-based values, and keyframes. You will also learn how to play animations in sequence using timelines.

Specifying Property Values

Anime.js allows you to specify the final or end values for animatable properties of target elements. The initial or start value for the animation is the default value of that property. Any value specified in the CSS can also act as the start value. There are multiple ways of specifying an end value. 

It can also be a unitless number. In this case, the original or default units of the property are used while calculating any property values. You can also specify the value as a string, but the string must contain at least one numerical value. Examples of string values would be 10vh, 80%, and 9.125turn.

Instead of specifying an absolute value, you can also specify property values relative to their current value. For example, you can set the final translateY value to be 150px greater than the current value using +=150px as a value. Keep in mind that you can only use addition, multiplication and subtraction while specifying relative values.

While animating colors, you cannot use color names like red, black and blue to set a final color value for the animation. In such cases, the color animation won’t happen at all, and the change will be instant. The only way to animate colors is to specify the values either as hex digits or in terms of RGB and HSL values.

As you might have noticed, we have not been specifying an initial value for our target elements to animate them. Anime.js automatically determines the initial value based on our CSS and the default values of those properties. However, you can specify an initial value other than the default value for a property using arrays. The first item in the array signifies the initial value, and the second item signifies the final value.

Instead of using the same final value for all your target elements, you can use functions to set different values for different parameters. The process is similar to specifying function-based property parameters.

For the translateY property, we are using the index of the element to set a translation value. Using 50 * (i + 1) increases the translateY value for each element by 50 pixels. 

The scaling animation also uses the index of the element along with the built-in Math.random() function to return a floating-point, pseudo-random number less than 1. This way the elements scale randomly, but the i/10 part of the property slightly increases the possibility of elements that occur in the end having a larger size.

Inside the code for rotation animation, we are using the anime.random(a, b) helper function to get random integers between -180 and 180. This function is helpful for assigning random integral values to properties like translateY and rotate. Using this function to assign random scale values will produce extreme results.

The border radius value for different elements is determined by calculating the width of target elements using the el function parameter. Finally, the last part of code assigns random values to the duration and delay parameters as well. 

You can see that the animation achieved by the last part is very random. There is no relation between the values of different properties of elements or their delay and duration values. In real life, it is more sensible to use values that can add some sense of direction to the animation.

It is also possible to animate different properties of your target elements using keyframes. Each keyframe consists of an array of the property object. You can use the object to specify the property value, duration, delay and easing for that part of the animation. The following code creates a keyframe-based translation animation.

You can also animate multiple properties at once by specifying different or the same values for all the parameters. In the second case, the global delay parameter applies an initial delay to all the elements based on their index. This delay is independent of the delay applied to each property inside the keyframes.

Creating and Manipulating Timelines

So far in the series, we have been using the delay parameter to play different animations in a specific sequence. To use delay for this purpose, we also need to know the duration of the previous animation. 

With the increasing complexity of the animation sequence, maintaining the right delay value becomes very tedious. Any change in the duration of one of the animations will force us to recalculate all the delay values to keep the animations in the original sequence.

A better solution to this problem is using timelines to control the animation sequence. You have to use the anime.timeline() function to create a timeline in Anime.js. You can also pass different parameters to this function as an object. These parameters can specify the direction in which the timeline is played, the number loops, and an autoplay parameter to determine if the animation should be auto-played. All these parameters have been discussed in detail in the parameters tutorial of this series.

You can add different animations to a timeline using the add() method. All the animations added to the timeline will be played in the order in which they were added. It is possible to specify absolute or relative offset values to control the order in which the animations are played. 

When relative offset values are used, the starting time of the current animation is determined relative to the timing of the previous animation. Relative offsets can be of three types:

  • +=offset: In this case, the current animation starts playing after offset number of milliseconds have passed since the end of the previous animation.
  • -=offset: In this case, the current animation starts playing offset number of milliseconds before the end of the previous animation.
  • *=offset: In this case, the current animation starts playing after milliseconds equal to offset times the animation duration of the previous animation have passed.

The following code shows how to create a basic timeline and a timeline with relative offset values.

Try clicking the Offset Timeline button in the above demo. You will see that there is a delay of 2 seconds between the end of the animation of red squares and the beginning of the animation of blue squares. 

We have not specified a duration for the red square animation. Therefore, a default value of 1000ms or 1s is used as duration. The multiplier offset of the blue square animation doubles that value, and this results in a delay of two seconds in the animation.

When absolute offset values are used, the starting time of the timeline is used as a reference point. It is possible to reverse the sequence in which the animations are played by using large offset values for animations that occur at the beginning of the timeline.

Playback Options

Anime.js has a variety of options to play, pause, restart or seek animations or timelines at any given point.

The play() function allows us to start the animation from its current progress. The pause() function will freeze the animation at the moment the function was called. The restart() function starts the animation from the beginning, irrespective of its current progress. The seek(value) function can be used to advance the animation by value number of milliseconds.

You should keep in mind that the play() function only resumes the animation from the time it was paused. If the animation has already reached its end, you cannot replay the animation using play(). To replay the animation, you will have to use the restart() function.

Note that we are not using seekInput.value to set a value for the seek function. This is because the max value for the range input has been set to 100 in the markup. Directly using the value for input range will allow us to only seek up to 100ms. Multiplying the range input value with the animation duration makes sure that we can seek the animation from the beginning to the end on our range slider.

Final Thoughts

In this tutorial, you learned how to animate different property values as numbers, functions, or keyframes. You also learned how to control and manipulate timelines in Anime.js to control the order in which an animation sequence is played.

If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

If you have any questions related to this tutorial, please let me know in the comments.


Source: Nettuts Web Development

JavaScript Design Patterns: The Observer Pattern

In JavaScript, there is a problem that comes up often. You need a way to update parts of a page in response to certain events, with the data these provide. Say, for example, user input that you then project into one or many components. This leads into a lot of push-and-pull in the code to keep everything in sync.

This is where the observer design pattern can help — it enables one-to-many data binding between elements. This one-way data binding can be event driven. With this pattern, you can build reusable code that solves for your specific needs.

In this article, I’d like to explore the observer design pattern. It will help you solve a common problem you see in client-side scripting. That is one-to-many, one-way, and event-driven data binding. It is a problem that comes up often when you have many elements that must be in sync.

I’ll use ECMAScript 6 to illustrate the pattern. Yes, there will be classes, arrow functions, and constants. Feel free to explore these topics on your own if you are not already familiar. I’ll use parts of ES6 that introduce syntactic sugar only, so it is portable with ES5 if need be.

And I’ll use Test-Driven-Development (TDD) to work on the pattern. This way you have a way knowing how each component is useful.

The new language features in ES6 make for some succinct code. So, let’s get started.

The Event Observer

A high-level view of the pattern looks like this:

EventObserver
│ 
├── subscribe: adds new observable events
│ 
├── unsubscribe: removes observable events
|
└── broadcast: executes all events with bound data

After I flesh out the observer pattern I’ll add a word count that uses it. The word count component will take this observer and bring it all together.

To initialize the EventObserver do:

class EventObserver {
  constructor() {
    this.observers = [];
  }
}

Start with an empty list of observed events, and do this for every new instance. From now on, let’s add more methods inside EventObserver to flesh out the design pattern.

The Subscribe Method

To add new events do:

subscribe(fn) {
  this.observers.push(fn);
}

Grab the list of observed events and push a new item to the array. The list of events is a list of callback functions.

One way to test this method in plain JavaScript is as follows:

// Arrange
const observer = new EventObserver();
const fn = () => {};

// Act
observer.subscribe(fn);

// Assert
assert.strictEqual(observer.observers.length, 1);

I use Node assertions to test this component in Node. The exact same assertions exist as Chai assertions too.

Note the list of observed events consists of humble callbacks. We then check the length of the list and assert that the callback is on the list.

The Unsubscribe Method

To remove events do:

unsubscribe(fn) {
  this.observers = this.observers.filter((subscriber) => subscriber !== fn);
}

Continue reading %JavaScript Design Patterns: The Observer Pattern%


Source: Sitepoint

Learn Plugin Development with a Bulk Category Creator

In this tutorial, you will begin to learn plugin development for WordPress. The example plugin will have an admin page with a basic form element and a submit button, and will perform the simple task of creating bulk categories in one go.

A lot of times, when developing a website or blog on WordPress, you would need to create a lot of categories. In these instances, it can become a pain to create categories one by one. So, in this tutorial you will learn to build a plugin which allows a list of comma separated categories to be copy pasted into a text area. And on clicking a button, all the categories are loaded into the WordPress categories section in a single go. So, this will prevent the need to sit and click on the Add New Category button for every category that has to be created.

Requirements:

  1. You will need a local installation of WordPress (or a development server of some kind)
  2. You will need to know basic HTML and PHP

What are you going to build (Preview of the final stage of what you are going to create)

Bulk Category Creator

A Brief Note About WordPress Plugins

Plugins in WordPress are basically PHP scripts which allow you to change or add new features to your existing WordPress installation. It could be something really simple, like the “Hello Dolly” plugin, or something really advanced like the Jetpack or Google Analytics plugins.

So, why should you build a plugin?

Most WordPress developers are aware that they should not hack WordPress core files to suit their needs. It creates updating issues, and could be insecure. But if altering WordPress core code is not a good option, how else will you add new features to your WordPress website? The answer, of course, is via plugins. An added benefit to learning how to create plugins is that you get to learn more about WordPress itself, and how it works. That in turn will make you a better WordPress Developer.

Learning Plugin Development

In order to create a plugin, you have to create a particular folder structure for your plugin. Every plugin has a directory name and one or more PHP files inside it.

Inside your WordPress directory structure, you will find a directory called wp-content. Inside the wp-content will be a directory called plugins.

Your folder structure would look similar to this:

File Structure

First Steps – Creating Your Files

The very first step in creating a plugin is to navigate to the wp-content directory of your WordPress installation and inside the directory navigate to the plugins directory. Inside the plugins directory create a new directory called bulk-category-creator.

Once, you have created the directory, create a file named bulk-category-creator.php. Make sure that the directory name and the PHP file name are the same.

Now, open your text editor and copy paste the following code into it

<?php
   /*
   Plugin Name: Bulk Category Creator
   Plugin URI: http://www.ruforaweb.com
   Description: A plugin to bulk-create categories in one go
   Version: 1.0
   Author: Vishnu Ajit
   Author URI: http://twitter.com/vishnuajith310
   License: GPL2
   */

Every plugin has a section of code comments at the top containing a description, version information, author name and licensing information. This is usually found in the header of the plugin’s main file. In our case, it is found in bulk-category-creator.php.
This section is the metadata of the plugin. Let us dissect the example metadata line by line.

  • Plugin Name: Here is the name given to the plugin, in our case we call it the Bulk Category Creator
  • Plugin URI: This is a link to where the plugin can be found on the internet for download purposes. It can be found in the WordPress.org archives or in another location.
  • Description: This is the section where you can describe what actions the plugin performs.
  • Version: Specifies the version of the plugin
  • Author: Name of the author or developer who created this plugin
  • Author URI: Link to the author’s address on the internet
  • License: The license under which this plugin is released

Navigate to your Admin Dashboard > Plugins > Installed Plugins and you should see your plugin in the list.

Code Layout – Bulk Category Creator Plugin

Before jumping into coding our plugin, let us understand some basic WordPress hooks.
Basically, in WordPress there are two main types of hooks: Actions and Filters. Since, this is a basic plugin development tutorial, we shall not go into too much detail, but basically this is how they differ.

  • Actions: Actions are used when you add something when an event has occurred. Example: an action to tweet an article when a new post has been published.
  • Filters: Filters are used when you have to change some data or process it.

Now that you are familiar with the basics, let us start coding our plugin.

add_action('admin_menu', 'rfr_CategoryCreatorMenu');

This line of code hooks the admin_menu to the function rfr_CategoryCreatorMenu

The admin_menu function is used to add submenu or menu options to our WordPress Admin Dashboard. Once that has been done, write down the next snippet of code.

Continue reading %Learn Plugin Development with a Bulk Category Creator%


Source: Sitepoint

3 Unexpected Signals Employers Send Before They Fire You

startled rabbit

You’re afraid.

If you’re like most web developers, you often worry about losing your job. The fear is always there, lurking in the back of your mind.

Am I next?

Most employers are seen as disloyal. If push comes to shove, they’re more than happy to show you the door. When they do, it feels like a betrayal.

For Employers, It Isn’t a Betrayal

It’s just business.

At least, that’s what we’re expected to believe. Dig a little deeper, and we see that employers and developers …

  1. … don’t trust each other. It’s common for developers and employers to distrust each other from the very beginning. Salary negotiations are focused on squeezing as much value out of the other side, while minimizing what’s offered in return.

  2. … rarely build a stable relationship. The employee/employer relationship is unsafe. Say the wrong thing, or say No to your boss, and you risk losing your career.

  3. … are inward focused. For the most part, developers and employers are focused on themselves — because both sides feel they have to be.

  4. … lack loyalty. For most, long and medium term employment has become a thing of the past. Some believe long term loyalty affects your value in the marketplace.

It isn’t just business, but even so …

Sometimes Your Employer Just Wants to Get Rid of You

Maybe you’ve lost the office politics game. It could be that your employer’s about to lose a major client, forcing them to lay you off. Maybe something’s gone wrong and you’re the scapegoat. Whatever the reason, your employer may feel the need to dump you.

What does this mean for you, the developer? At some point in your career you’ll be fired, laid off, demoted or aggressively “encouraged to quit.”

Most developers never see it coming.

Is that even possible? Is it possible to spot warning signs indicating you’re about to lose your job, way ahead of time?

Absolutely.

I’m not talking about the obvious signs — such as your boss announcing layoffs, or that your company isn’t doing well, etc.

Waiting for these signs means it’s too late. I’m talking about signs lurking in the background.

You’re About to Be Fired. The Signs Are There If …

You know where to look. The usual signs aren’t all that helpful, because it’s usually too late to do anything. If you’re waiting for …

  • management to announce layoffs
  • your boss to mention they’ve lost a major contract
  • your unpredictable workload to resolve itself

… you won’t have time to act when the announcement comes. You need a different set of tools. These tools need to (a.) give you plenty of time to act, (b.) be a reliable predictor, and (c.) give you options. One more thing. These signals require three things:

  1. some digging (don’t worry it’s simple and easy)
  2. understanding the information you dig up
  3. an understanding that these signals are about the business, not you.

Let’s look at the first signal.

Signal #1: You’re not part of the in-group

A meta-analysis conducted by Talya Bauer et al. discovered that feeling socially accepted was a key factor in employee success.

If you’re part of the group, you stay.

More importantly than that, they make the companies they serve more successful. But why do things work out that way? Because becoming part of the group gives everyone greater access to information and resources.

You share information and resources you have with the rest of the team, and they (your coworkers and the business) share with you.

This may not seem like much, but it’s vital. It’s vital because it’s the only way you’re able to demonstrate your value.

Reddit user FiletOfFish1066, has just been fired from his programming job at a major tech company. He was employed for six years receiving an annual salary of $95,000. What did he give his employer in return?

Nothing.

From around 6 years ago up until now, I have done nothing at work. I am not joking. For 40 hours each week I go to work, play League of Legends in my office, browse Reddit, and do whatever I feel like. In the past 6 years I have maybe done 50 hours of real work. So basically nothing. And nobody really cared. The tests were all running successfully. I shit you not, I had no friends or anything at work either, so nobody ever talked to me except my boss and occasionally the devs for the software I was testing.

Here’s the amazing part. This developer actually gave his employer an incredible gift.

He figured out how to automate his job completely. Let’s say there were just 10 to 20 people in his department. That’s $1,000,000–$19,000,000 per year he could’ve saved his employer.

That’s leverage he could have used to bargain for a raise. If his employer refused, he could have taken that information to another company, or started his own business.

So, what’s the lesson here?

If you’re a developer who’s not part of the group, not socially accepted, it’s a signal you’re expendable. When disaster strikes, you’ll be the first to go.

Signal #2: Sales, growth and profit blindness

Developers, as a general rule, despise marketers and salespeople. We don’t trust them because they’re usually not very technically literate. Naturally this means many of them will lie to get what they want. They’ll do or say anything to make the sale.

That makes sense, right?

Our disdain for sales and marketing folks is based on their behavior, which can be pretty terrible.

Here’s the problem.

Your salary comes from sales and marketing. It’s how you measure employer health. Are they bleeding money? Is the market dying? Are they up to their eyeballs in debt?

If you want to keep your job, you’ll need to understand sales and marketing — namely, how sales and marketing is done at your company.

When it comes to sales and marketing, the vast majority of companies have some pretty bad habits. These bad habits make job security impossible.

These bad habits create business disasters that lead to job loss — whether it’s furloughs, firings or layoffs. Okay. What kinds of habits?

  • Sales/revenue has dropped 2 years in a row. This could be a result of several factors. Dying industries like newspapers, automation in the taxi and delivery industries, or poorly managed companies like Kodak who created the digital camera in 1975 but never let it see the light of day.

  • Nobody knows where profits come from. Remember K-Mart? No one — employees, management or even vendors — knew which products were profitable. No surprise then that they’re circling the drain, continually laying off employees. Employees make fantastic decisions when they know which products have the highest margins and perform best for the company.

  • Sales force focused on volume instead of profit. Experts tell us “sales fixes everything.” But it doesn’t. Sales fixes everything if there’s profits, money left over at the end. That’s a problem, because sales often creates expenses. When there’s little to no profit, there’s little to no money to pay employees, which means furloughs, firings, and layoffs will follow.

  • Sales/revenues are 2x larger than net profits. Disaster is inevitable — a recession, investors drying up, a dying industry. When there’s profit you have a job, when these disasters hit there simply won’t be any money left to pay you. The business will either (a.) terminate as many employees as possible or (b.) keep everyone on board and die a slow, painful death.

See the problem?

Any problem that hurts your employer’s finances, eventually hurts you.

If you deliver results — money, connections, resources, time — you’re far more likely to weather the inevitable storm. But most employees won’t do the work to create transformative change for their employer.

So, they’ll lose their jobs.

Continue reading %3 Unexpected Signals Employers Send Before They Fire You%


Source: Sitepoint

Friendly, Frictionless Work: Best Practices For Enterprise Messaging UX, From Slack




 


 

Creating good user experiences for apps inside messaging platforms poses a relatively new design challenge. When moving from desktop web to mobile interfaces, developers have had to rethink interaction design to work around a constrained screen size, a new set of input gestures and unreliable network connections.

Friendly, Frictionless Work: Best Practices For Enterprise Messaging UX, From Slack

Like our tiny touchscreens, messaging platforms also shake up the types of input that apps can accept, change designers’ canvas size, and demand a different set of assumptions about how users communicate.

The post Friendly, Frictionless Work: Best Practices For Enterprise Messaging UX, From Slack appeared first on Smashing Magazine.


Source: Smashing Magazine