Thursday, May 4, 2017

Create an Animated Sticky Navigation Menu with Vanilla JavaScript

When adding a navigation menu to a webpage, there are a lot of things to take into consideration. For example where to position it, how to style it, how to make it responsive. Or maybe you want to add some kind of animation to it (tastefully, of course). At this point you might be tempted to grab a jQuery plugin which does most of that for you. But that needn't be! It's actually pretty simple to create your own solution in a few lines of code.

In this post, I will demonstrate how to create an animated, sticky navigation menu with vanilla JavaScript, CSS and HTML. The final product will slide up out of your way as you scroll down the page, then slide back into view (with a stylish see-through effect) when you scroll back up. This is a technique used by such popular sites, such as Medium and Hacker Noon.

After reading you'll be able to employ this technique in your own designs, hopefully to great effect. There's a demo at the end of the article for the impatient.

The Basic HTML Structure

The following is the skeleton HTML code that we will be working with. Nothing too exciting going on here.

<div class="container">
  <div class="banner-wrapper">
    <div class="banner">
      <div class="top">
        <!-- Navbar top row-->
      </div>
      <div class="nav">
        <!-- Links for navigation-->
      </div>
    </div>
  </div>

  <div class="content">
    <!-- Awesome content here -->
  </div>
</div>

Applying a Little Styling

Let's add some styling to the main elements.

Main Container

We'll need to remove any inherent browser styles and set the width of our container to 100%.

*{
  box-sizing:border-box;
  padding: 0;
  margin: 0;
}

.container{
  width: 100%;
}

Banner Container

This is a wrapper around the navigation menu. It is always sticky and slides to hide or reveal the navigation menu as you scroll your page vertically. We are giving it a z-index value to ensure that it appears on top of the content.

.banner-wrapper {
  z-index: 4;
  transition: all 300ms ease-in-out;
  position: fixed;
  width: 100%;
}

Banner Section

This contains the navigation menu. Changes in position and background color are animated through the CSS transition property when a page is scrolled up or down.

Continue reading %Create an Animated Sticky Navigation Menu with Vanilla JavaScript%


by Albert Senghor via SitePoint

Three Ways of Decreasing SVG File Size with SVGO

Three Ways of Decreasing SVG File Size with SVGO

This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.

In this article I suggest three ways in which SVGO lets you optimize SVG graphics to make them suitable for web use.

Why You Need to Optimize SVGs

SVG (a.k.a. Scalable Vector Graphics) is a resolution-independent graphics format. The big advantage of not being pixel-based is that SVGs look awesome on our shiny retina screen-enabled devices and work great on the responsive web.

If like me you're not a graphic designer, you might have found yourself grabbing ready-made SVGs from various Creative Commons or Public Domain online sources. One downside of doing so is that often such artworks are not produced with the web in mind. This means that you might find they're rife with over-complicated paths and Photoshop-like effects. Also, since SVGs are XML-based, digging into the source code often reveals lots of unnecessary markup. Apart from my ingrained love for clean code, complexity and bloat add to the file size and negatively impact on website performance.

Don't think that if you draw SVGs yourself you'll be totally in the clear. Although the latest versions of Adobe Illustrator make it possible to export reasonably clean SVG markup, older versions, as well as some different vector graphics editors, still sprinkle the markup with unneeded comments, doctype declarations and proprietary attributes.

Here's an instance of graphics editor-generated code to illustrate the point:

[code language="html"]
<svg
xmlns:rdf="http://ift.tt/oZyhLL"
xmlns:svg="http://ift.tt/nvqhV5"
xmlns="http://ift.tt/nvqhV5"
xmlns:inkscape="http://ift.tt/W45utL"
viewBox="0 0 1000 1000" version="1.1">

<g inkscape:label="Katze" inkscape:groupmode="layer" id="layer1" transform="translate(0,-52.362183)">

... More code here

</g>

</svg>
[/code]

Instead, all you really need is:

[code language="html"]
<svg
xmlns="http://ift.tt/nvqhV5"
viewBox="0 0 1000 1000">

<g id="layer1" transform="translate(0,-52.362183)">

... More code here

</g>

</svg>
[/code]

Furthermore, if you don't use layer1 in your CSS or JavaScript, you could get rid of the id attribute on the <g> tag as well.

Personally, I'm in favor of a bit of manual cleaning up of SVG code. But, fear not, the bulk of the most tedious and repetitive part of the optimization work easily lends itself to automation.

What Is SVGO?

Without a doubt, the most popular tool available for the job at this time is SVGO.

SVGO runs on Node.js, an asynchronous, event-driven runtime to build scalable network applications. You don't need to know how to build applications with Node.js in order to work with SVGO. However, you need to use your computer's command line user interface (CLI).

SVGO allows you to enable or disable specific optimizations by enabling or disabling its plugins.

For instance, if you want to remove empty attributes from your SVG graphic, you'll have to enable the removeEmptyAttrs.js plugin.

You can see a full list of all the available plugins for SVGO in the project's README file on GitHub.

There are quite a few ways in which you can integrate SVGO in your development work. In what follows, I'm going to discuss just three of the options open to you.

#1. Just Node.js and SVGO

To start using SVGO, just install Node.js by downloading the latest stable version corresponding to your operating system and follow the instructions in the installer.

Next, you can install SVGO using npm, Node's package manager. Type this command in your terminal:

[code language="bash"]
npm install -g svgo
[/code]

Now, you have installed SVGO globally in your machine so you can use it anywhere.

To optimize an SVG file, type in your terminal:

[code language="bash"]
svgo yoursvgfile.svg
[/code]

Replace yoursvgfile.svg with the name of the SVG file you wish to optimize. However, using the tool this way destroys the original file, which is something I wouldn't recommend. In fact, you might want to make changes to the original file, and destroying all the editor-specific code might prevent you from being able to use your graphics program's editing features. Therefore, it's best practice to generate a new, optimized file without overriding the original one. To do so, type this command:

[code language="bash"]
svgo yoursvgfile.svg yoursvgfile.min.svg
[/code]

Now, you have two SVG files: yoursvgfile.svg, which is the original file, and yoursvgfile.min.svg, which is the optimized SVG file.

I've just performed this step and SVGO lets me know that in just 167 milliseconds it created an optimized copy of the original file. The latter weighed 17.9 Kb while the optimized copy weighs 11.48 Kb, yielding a 36.2% saving:

Message after SVGO performs its SVG file optimization.

If you open yoursvgfile.min.svg in a text editor, you'll see much less code, which means a much smaller file size. Great!

You can also point SVGO to an entire folder using the -f flag, like this:

[code language="bash"]
svgo -f ../path/to/folder/with/svg/files
[/code]

To customize the output SVGO generates, enable the many plugins available. For instance:

[code language="bash"]
svgo yoursvgfile.svg --enable='removeComments,mergePaths'
[/code]

The command above creates an optimized version of yoursvgfile.svg by removing comments and merging multiple paths in the source code.

#2. Integrate SVGO in Your Gulp Workflow

A widely adopted front-end workflow these days includes a task runner that performs automated operations like compiling Sass into CSS, minifying scripts, etc.

One of the most popular task runners is Gulp, which is both powerful and quick to implement.

It's easy to integrate SVGO with your Gulp-based workflow thanks to gulp-svgmin.

You install gulp-svgmin with npm:

[code language="bash"]
npm install gulp-svgmin
[/code]

A basic gulp task for svgmin looks like this:

[code language="js"]
var gulp = require('gulp');
var svgmin = require('gulp-svgmin');

gulp.task('default', function () {
return gulp.src('logo.svg')
.pipe(svgmin())
.pipe(gulp.dest('./out'));
});
[/code]

The code above, which you add to your Gulp configuration file, Gulp.js, takes logo.svg, calls svgmin to optimize it, and outputs it in a dedicated folder.

You can find more articulated examples on the gulp-svgmin GitHub page. If you're not all too familiar with Gulp but you'd like to get up to speed with it, don't miss An Introduction to Gulp.js by Giulio Mainardi, which offers an easy-to-follow walk-through.

#3 SVGOMG: The Online GUI Version of SVGO

Command line tools are practical and get the job done quickly. However, nothing beats having a preview of your SVG graphic while you're optimizing it.

Continue reading %Three Ways of Decreasing SVG File Size with SVGO%


by Maria Antonietta Perna via SitePoint

Tackling Render Blocking CSS for a Fast Rendering Website

Tackling Render Blocking CSS for a Fast Rendering Website

This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.

I've always thought deciding how and when to load CSS files is something best left to browsers. They handle this sort of thing by design, why should developers do anything more than slap a link element with rel="stylesheet" and href="style.css" inside the <head> section of the document and forget about it?

Apparently, this may not be enough today, at least if you care about website speed and fast-rendering webpages. Given how both these factors impact on user experience and the success of your website, it's likely you've been looking into ways in which you can gain some control over the default way in which browsers deal with downloading stylesheets.

In this article, I'm going to touch on what could be wrong with the way browsers load CSS files and discuss possible ways of approaching the problem, which you can try out in your own website.

The Problem: CSS Is Render Blocking

If you've ever used Google Page Speed Insights to test website performance, you might have come across a message like this:

Message from Google Page Speed Insights about render blocking CSS.

Here Google Page Insights is stating the problem and offering a strategy to counteract it.

Let's try to understand the problem a bit better first.

Browsers use the DOM (Document Object Model) and the CSSOM (CSS Object Model) to display web pages. The DOM is a model of the HTML which the browser needs in order to be able to render the web page's structure and content. The CSSOM is a map of the CSS, which the browser uses to style the web page.

CSS being on the critical rendering path means that the browser stops rendering the web page until all the HTML and styles information are downloaded and processed. This explains why both HTML and CSS files are considered to be render blocking. External stylesheets especially involve multiple roundtrips between browser and server. This may cause a delay between the time the HTML has been downloaded and the time the page renders on the screen.

The problem consists in this delay, during which users could be staring at a blank screen for a number of milliseconds. Not the best experience when first landing on a website.

The Concept of Critical CSS

Although HTML is essential to page rendering, otherwise there would be nothing to render, can we say the same about CSS?

Of course, an unstyled web page is not user friendly, and from this point of view it makes sense for the browser to wait until the CSS is downloaded and parsed before rendering the page. On the other hand, you could argue that not all style information is critical to building a usable page. What users are immediately interested in is the above the fold portion of the page, that is, that portion which users can consume without needing to scroll.

This thought is behind the dominant approach available today to solve this problem, including the suggestion contained in the message from Google Page Insights reported above. The bit of interest there reads:

Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

But how do you defer or asynchronously load stylesheets on your website?

Not as straightforward as it might sound. You can't just toss an async attribute on the link element as if it were a <script&gt
tag.

Below are a few ways in which developers have tackled the problem.

Take Advantage of Media Types and Media Queries to Minimize Render Blocking

Ilya Grigorik illustrates a simple way of minimizing page rendering block which involves two stages:

  • Split the content of your external CSS into different files according to media type and media queries, thereby avoiding big CSS documents that take longer to download
  • Reference each file with the appropriate media type and media query inside the link element. Doing so prevents some stylesheet files from being render blocking if the conditions set out by the media type or media query are not met.

As an example, references to your external CSS files in the <head> section of your document might look something like this:

[code language="html"]
<link href="style.css" rel="stylesheet">
<link href="print.css" rel="stylesheet" media="print">
<link href="other.css" rel="stylesheet" media="(min-width: 40em)">
[/code]

The first link in the snippet above doesn't use any media type or media query. The browser considers it as matching all cases therefore it always delays page rendering while fetching and processing the resource.

The second link has a media="print" attribute, which is a way of telling the browser: "Howdy browser, make sure you apply this stylesheet only if the page is being printed". In the context of the page simply being viewed on the screen, the browser knows that stylesheet is not needed, therefore it won't block page rendering to download it.

Finally, the third link contains media="(min-width: 40em)", which means that the stylesheet being referenced in the link is render-blocking only if the conditions stated by the media query match, i.e., where the viewport's width is at least 40em. In all other cases the resource is not render blocking.

Also, take note that the browser will always download all stylesheets, but will give lower priority to non-blocking ones.

To sum up, this approach doesn't completely eliminate the problem, but can considerably minimize the time browsers block page rendering.

Using the preload Directive on the Link Element

Continue reading %Tackling Render Blocking CSS for a Fast Rendering Website%


by Maria Antonietta Perna via SitePoint

Quick Tip: How to Automate Social Media Posting with Jetpack

In this article, you will learn how to use Jetpack’s social media functionality to augment your Wordpress site. Depending on where you get your copy of WordPress, Jetpack might be a part of the installation – or not. Here you can take a look at setting up your installation if Jetpack is not included.

To get started, go to Jetpack.com. As you can see, there are two options, the free install or pricing. In this tutorial you'll see the free installation.

When you click on the Install Free button, the screen above appears. Enter the full URL of your WordPress site. When you do, the blue Start Installation button appears. Click on it to begin installing Jetpack.

On the screen above, click on Install Jetpack.

This takes you to yet another screen. Click on the blue Install Now button at lower-right.

This redirects you back to WordPress, where you are informed that Jetpack has been successfully installed. Click on the Blue Activate Plugin button to activate Jetpack.

At this point, you will come to a screen which could look like the above. This will allow you to connect Jetpack (via WordPress.com) to your installation.

When you press on the connection button, if you don't have an active session at WordPress.com, it will bring up a login screen where you must sign into WordPress.com to connect Jetpack.

Once you click on the blue button to connect your account, you will be redirected back to your installation, where you should click Jetpack in the sidebar.

Continue reading %Quick Tip: How to Automate Social Media Posting with Jetpack%


by Nathan Segal via SitePoint

Using DeployHQ to Automate Your Deployments

The Problem: Deploying Code

So you have your projects in GitHub. Whatever they are - an app you're working on with a small team. A small business brochure site. An ecommerce platform. You've decided to version control them, but you still have little in the way of automated processes in place, and you're still having to update each of your environments - staging, production, whatever you have - by hand, with FTP. Or you've got them pulling down Git changes from a branch.

This pain is only multiplied if you're deploying to other development or staging servers too, beyond just one, or you have a load balanced production machine that needs multiple simultaneous deployments. What you really need is an automated process here, that can either automatically deploy when changes to code are made, or can be ready to do so at the push of a button.

The Solution: DeployHQ

DeployHQ can be the link between your Git repository and your servers and do your deployments for you. You can make those deployments automatic (every time you commit to your staging branch, DeployHQ automatically deploys those changes to your Staging server). You can also trigger deployments manually though (deploying to Production server from the production branch requires you to push the button yourself). This flexibility allows for a maximum of convenience and automaton without taking some safeguards away, like a review of code merged into production, or the schedule by which you update your production website.

DeployHQ seems especially good for a small company or developer who doesn't have all of their testing, builds, CI, etc automated yet into cohesive processes, and is really looking for a way to push code to various environments with as little friction as possible.

Getting Started with DeployHQ

When you sign up for your DeployHQ account, you'll login and arrive at the welcome screen.

Then, you'll need to follow a few steps in order to get your deployments up and running!

1) Preparation

In the below examples of configuration, GitHub will be used as the version control system. So, head over to GitHub, and if you don't already have a project in mind, create a repository. The repository, ideally, will have multiple branches (i.e. "staging", "production") just to help demonstrate the functionality available at DeployHQ. Both staging and production branches of a test repository will be used in this demonstration. You can leave this open in a tab, as you'll need to come back.

2) Create a New DeployHQ Project

Right from the welcome screen, hit the "Create a new project" button.

You'll need to give the project a name, and choose the version control system that you're using. For this example, we're using GitHub. Then, hit "Create Project"! You'll see a progress screen, and then, if all goes well, you'll get a screen that requires you to login (or if already logged in, authorize the app) to access your repository.

Once you've authorized DeployHQ to access your GitHub, you'll be taken to a screen which shows the organizations you're connected to (and your personal repositories) with a list of those repositories. Pick one to link your project to, and once this is done, DeployHQ will ask you to provide server information.

Continue reading %Using DeployHQ to Automate Your Deployments%


by Jeff Smith via SitePoint

What? Why Would Someone Hack My Small Business Website?

The traditional media representation of a hacker

You are an entrepreneur, manager or a marketing pro responsible for the website in a company which is simply meant as a digital business card to introduce the company, its services, and the latest news. Not including any state secrets, right.. so why are they still doing this?

But then again.. once in a while you might encounter this kind of messages.

Making money (a lot of money).

Yes, even a small website hack can generate a substantial amount of money. Cyber criminals can make money with your compromised website by distributing malware, SEO spam, and even set up e-mail spam servers and phishing sites.
Money is obviously the most common motivation behind the attacks.

Continue reading %What? Why Would Someone Hack My Small Business Website?%


by Oliver Sild via SitePoint

8 of the Best Plugins for Optimizing WordPress Site Performance

How do you avoid having a website that’s as slow as molasses? Our last article detailed ten techniques for optimizing your WordPress performance. This follow-up post is a quick reference of the best plugins that satisfy your need for speed.

We’ve covered eight of the best plugins that cover all the bases. We’ve also listed almost two dozen alternatives so you can explore which best suit your needs. Dive in and see what makes the most difference to your site.

If you’re following our WordPress Maintenance Checklist you’ll probably already be using some of these plugins. Keep it up! That cruft will continue to accumulate.

Have we missed your favorite plugin? How has it helped? Let us know in the comments.

1. W3 Total Cache

  • Cost: free
  • Active installs: 1+ million

This plugin provides Easy Web Performance Optimization (WPO) using caching—caching of posts and pages to memory or disk, caching of feeds, search result pages, database objects and minified CSS and Javascript files. To get the most out of it, spend some time configuring it carefully.

W3 Total Cache can also work with your CDN (like Cloudflare or MaxCDN) to further improve load times.

W3 Total Cache improves the SEO and user experience of your site by increasing website performance, reducing download times via features like content delivery network (CDN) integration.

Alternative caching plugins include WP Super Cache, Hyper Cache, WP Fastest Cache and Cache Enabler.

2. WP-Optimize

  • Cost: free
  • Active installs: 600,000+

This free plugin will optimize your WordPress database with the click of a button, or automatically with its built-in scheduler. Redundant information like spam comments, post revisions and other trash items will be cleaned from your mySQL database, speeding up how quickly your site loads.

WP-Optimize is an effective tool for automatically cleaning your WordPress database so that it runs at maximum efficiency.

Alternative database optimization plugins include Optimize Database after Deleting Revisions, WP Cleanup, WPOptimize, WP Database Cleaner and WP-DBManager.

Continue reading %8 of the Best Plugins for Optimizing WordPress Site Performance%


by Adrian Try via SitePoint