Archiwum kategorii: CSS

Using CSS Clip Path to Create Interactive Effects

Post pobrano z: Using CSS Clip Path to Create Interactive Effects

Do you remember being a kid, cutting out pictures from magazines? Did you glue them onto paper to create your own collages? This post is about cutting out images on the web using the CSS property clip-path. We will discuss how to do the cutting and how we can use these cut-out parts to create some interesting effects, combining these cut-out parts with the original image.

I’ll use the following photo as an example. The flower stands out from the rest of the photo. It is a natural focal point to cut out and create our effects around.

Hand holding a flower
Image courtesy of Unsplash. Credit: Hermes Rivera

Creating the SVG

First off, we are going to create a new SVG file and import our example image into it. You will need image editing software with vector capability to make the cut. I’m using Inkscape, a free open source editor, but you can apply the same method covered in this post using other applications such as Adobe Illustrator or even an online editor, like Vectr.

Let’s start out by creating a new 100px square SVG document in the image editor. It’s important to use a 100px square because clipping paths come in length-percent. Choosing a 0-100 scale will allow for seamless conversion from pixel to percent.

One thing that I find very valuable before proceeding is to examine the SVG code output from the editor. Getting that output depends on the application. For example, there are two methods in Illustrator alone. Looking at the markup gives us insight into what the editor is doing behind the scenes because not all applications export SVG the same way. Seeing the code will increase your understanding of the markup. It’s a win-win.

The SVG output should give us something like this:

<svg … width="100px" height="100px" viewBox="0 0 100 100" …>
	...
</svg>

One of the more important parts of the above is the viewBox attribute because it represents the internal coordinate system of the SVG document. Here’s a thorough explanation of how it works. Above, we can see that the document has the correct proportions where width, height and viewBox all span from 0 to 100.

Next up is importing the image. Here we’ll want to resize the image to 100px square and place it at the origin (0, 0). Doing so might break the aspect ratio of your image, unless your image is already in a square proportion. Our example image is not. This will not be a problem when applying clip-path later on.

Rescaling the image
The image is temporarily rescaled to meet the new square proportion.

Looking at the generated code once again, we now should see the <image> tag inside the SVG document. Note the preserveAspectRatio is set to none. This tells us that the image’s original dimensions are being ignored.

<svg … width="100px" height="100px" viewBox=“0 0 100 100”>
	...
  <image … y="0" x="0" xlink:href=".../image-file-name.jpg" preserveAspectRatio="none" height="100"
width="100" … />
	...
</svg>

Masking the Image File

Now for the actual image cutting.

The concept of cutting images is called masking. If you are unfamiliar with masking it’s essentially drawing a closed shape with the pen tool around an area of the image. You don’t need to be savvy with a vector editor to do this. It doesn’t require any particular artistic skills and it can be done in a few basic steps.

Masking digital images is very much like cutting images out of real magazines. The path created in the vector editor is the same you’d follow using a pair of scissors. Select the pen tool and start drawing the outline of the part of the image that you want to cut out. In this case, it’s the flower focal point we pointed out earlier. Create as many points you like along the way to shape the mask. Be sure to close the path as the last step.

It is important to only use cusp nodes when doing the cutting because clip-path does not support complex shapes, like Bezier curves at the time of this writing. It supports only simple shapes such as polygon, circle and ellipse.

If we view the SVG code now, the output will include a path with all the coordinates of the shape you drew. Here is an abbreviated example of my path’s output:

	...
	<path
		d="m 52.843605,79.860084 -0.69448,1.767767 -0.883884,0 -1.26269,-1.578364 -0.757615,0.06314 -1.388959,-2.714785 -0.12627,-2.967323 -1.704632,2.525381 -1.136422,-0.126269 -0.505076,-2.841054 -1.515229,1.325825 -1.325825,-0.126269 -0.252538,-1.578363 -0.947018,-0.126269 -0.252538,-0.315673 -0.947018,0.126269 -0.69448,-0.757614 0.126269,-1.641498 -0.441942,-0.252538 -0.189403,-2.588516 -0.505077,-0.06314 -1.010152,0.568211 -0.568211,-1.452094 0.441942,-2.399112 -1.325825,-0.126269 -0.378808,-1.262691 0.378808,-2.08344 0.883883,-1.641498 -1.010152,-1.26269 0.505076,-1.957171 -1.452094,-1.010152 -0.378808,-1.010153 1.136422,-2.209709 -2.209709,-0.378807 -0.441941,-1.704632 0.631345,-2.020305 1.704632,-1.38896 -1.578363,-1.452094 0.568211,-2.462247 0.820749,-0.441942 0.126269,-1.515229 0.757614,-1.073287 0.441942,-1.515228 -0.505076,-1.38896 0,-2.272843 0.505076,-1.010153 1.136422,-0.505076 1.325825,0 0.06313,-0.568211 -0.947018,-2.08344 0.378807,-0.631345 0,-0.441942 1.073288,-0.69448 1.073287,0 0.56821,0.315673 -0.189403,-2.525381 0.189403,-0.883884 0.378808,0.757615 0.06313,-0.883884 0.378807,-0.378807 0.189404,-0.378807 0.126269,-2.08344 0.315673,0.06314 0,-0.568211 0.378807,-0.06313 1.199556,0.568211 0.505076,0.69448 0.252538,-2.08344 0.631346,-0.505076 0.631345,-0.568211 0.441942,-0.505076 0.252538,0.505076 0,-0.883883 1.262691,0.315673 0.820749,-1.894036 1.325825,1.136421 1.073287,-1.452094 0.820749,0.189403 1.010152,1.515229 0.505077,0.757615 0.631345,-1.452095 0.820749,-0.56821 0.820749,0.505076 0.378807,0.631345 0.820749,-0.189403 0.820749,0.947018 0,0.252538 0.69448,-0.126269 0.378807,0.631345 0.820749,0 0.568211,1.515229 0.378807,1.325825 0.505076,-0.189404 0.252538,0.441942 0.378808,0.126269 0.441941,2.08344 0,0.568211 0.505077,-0.126269 0,0.883883 0.694479,-0.252538 0.505077,0.505076 0.252538,0.947018 0,0.883884 0.315673,0 0.378807,0.631345 0.441941,0.631345 0.06314,1.515229 -0.378807,1.957171 -0.441942,1.767767 2.904189,-1.136422 0.252538,0.631345 0.126269,2.209709 -0.883884,1.830902 1.38896,0.378807 1.010153,1.199556 -0.378808,1.641498 -0.947018,1.767767 -0.505076,0.378807 0.69448,1.767767 1.010153,1.26269 0.378807,1.38896 -0.378807,1.515229 -0.568211,0.315673 -0.505077,1.010152 -1.452094,0.883884 0.189404,1.325825 0.315672,0.883883 -0.378807,1.38896 -1.388959,1.073287 -0.505077,0.126269 0,0.505077 -0.189403,1.830901 -1.010153,0.631345 0.820749,2.209709 -0.631345,1.452094 -1.641498,-0.189403 0.126269,1.578363 -0.315673,1.641498 -1.073287,0.505076 -0.378807,0.315673 -0.378807,0.883883 -0.252538,1.010153 0.06313,2.714785 -0.631345,0.631345 -1.578364,-0.883883 -0.757614,-1.262691 -0.189404,2.462247 0.189404,2.083439 -0.252538,2.588516 -0.441942,1.894036 -0.631345,0.631346 -0.631345,-0.189404 -0.820749,-0.883883 z"
	/>
	...

Below is a video of me cutting out the flower and the result. The cutting took me about two minutes and the result is pretty decent.

Here is my image with a slight opacity on the mask to show the final shape that was cut out:

Converting SVG to CSS Clip Path

Now that we have the mask let’s have a look at how we go from SVG to clip-path. This means converting the path descriptor, or the d attribute in the SVG code.

Before we look into how to do the conversion, let’s talk a bit about the reasons for using clipping paths. You might ask why we’re creating a clipping path at all? Why not mask the image in the vector editor and export a pre-cut image? It’s possible and using images is a lot more convenient than working with a huge chunks of CSS code. But there are two principal benefits of going with the clipping path as I see it: interactivity and compression. SVG is essentially code in the DOM that can be manipulated and it is a much smaller file size than a bitmap image of the same shape.

The syntax for CSS clipping paths is somewhat the reverse of what it is in SVG. Pairs are comma-separated and spaces separate coordinates. This is the complete opposite to the SVG descriptor syntax. To further complicate the conversion, some shapes only use absolute coordinates. SVG paths are more flexible as they can use both coordinate systems.

I’ve created a rudimentary Node script that converts SVG paths. It takes paths in relative coordinates and outputs corresponding polygons using CSS clip-path. It uses regex to parse SVG files. Feel free to fork it and enhance it. One obvious addition would be to add normalization of proportions. Adding normalization would eradicate the need to only use square images when creating masks.

Here is the result of applying the clip-path to the photo of the flower:

See the Pen Cutting out images by Mikael Ainalem (@ainalem) on CodePen.

Tricks Using CSS Clip Path

Now that we have the cut-out part let’s have a look what we can with it.

Overlay Effect

One quite neat trick is to stack the cut-out part on top of the original image. Below is a pen illustrating the idea of overlaying the cut-out part on top of the original image. It will give you an idea of the positioning and the two different parts involved. Having these two different elements gives us the possibility to apply separate effects on the foreground and the background respectively.

See the Pen Cutting out images #2 by Mikael Ainalem (@ainalem) on CodePen.

Highlighting Effect

Highlighting parts on an image is not just visually appealing. It can also have a real impact on the user experience of your site. It isn’t hard to come up with useful scenarios where you might like to highlight parts of an image in a web page. Highlighting tagged people in a photo could be one use-case. Another could be to highlight certain features of a product in a product showcase. A third case could be a photo of a map, in which you would like to highlight places to do some storytelling around. Highlighting or emphasizing parts of the UI can when properly applied be powerful UX pattern. Using clipping paths is one way to achieve highlights in your UI.

Going back to the photo of the flower we can now easily make the flower stand out. One way to achieve this is to tone down the background behind the flower by lowering its opacity:

See the Pen Cutting out images #3 by Mikael Ainalem (@ainalem) on CodePen.

An interesting note is that the browser will hit-test the mask. Thus, to make it a bit more playful, we can trigger the highlight effect when the user hovers the flower. One way to do this is to add JavaScript event handlers (addEventListener) and attach them to the masked element. Setting these handlers to trigger on events like mouseenter and mouseout captures the user hovering the flower. We can even toggle classes on the background element to trigger the effect. A CSS opacity transition is essentially what’s needed.

See the Pen Cutting out images #4 by Mikael Ainalem (@ainalem) on CodePen.

There is nothing that prevents us from reusing the above technique several times in the same image. Here’s an example of highlighting many people in a photo. In this case there are several overlaid cut-outs:

See the Pen clip-path highlight by Mikael Ainalem (@ainalem) on CodePen.

Fading and Blurring Effects

An effect that we’ve been seeing more in the last year is blurred backgrounds. It’s kind of a reverse way to enhance foreground elements. Rather than enhancing the foreground element itself one can create the same effect by blurring background elements. This way of enhancing foreground elements has another pleasant side-effect: the element in your current focal point remains untouched. But, at the same time, it becomes more prominent.

The easiest way to achieve a blur effect is to use the CSS filter blur. The following pen uses the same JavaScript callback method as the previous example to trigger the effect on hover. Instead of toning down the background, it is blurred with a CSS filter transition.

See the Pen Cutting out images #9 by Mikael Ainalem (@ainalem) on CodePen.

Having a transition using the CSS filter, however, is very costly in terms of performance. This has to do with the shader running on the GPU used to create the blur effect. Animating the CSS blur filter is generally not a good idea. A more performant option is to reuse pre-filtered version of the image and use a cross-fade. In other words, we animate the opacity of a duplicated background image instead of animating the blur. Here is what that looks like:

See the Pen Cutting out images #10 by Mikael Ainalem (@ainalem) on CodePen.

Outline

Another option to reinforce the cut-out element is to use an outline effect. Reusing the mask is an easy way to make it. If we insert the SVG in between the two main elements and add a slight scale (1.04 in this case), we’ll make it appear as an outline.

See the Pen Cutting out images #5 by Mikael Ainalem (@ainalem) on CodePen.

Of course, we can also trigger the outline on hover like we did in the other examples:

See the Pen Cutting out images #6 by Mikael Ainalem (@ainalem) on CodePen.

The edges of the mask are a bit rough as the mask is binary. One option to soften the edges is to add an SVG filter. Here is an example:

See the Pen Cutting out images #8 by Mikael Ainalem (@ainalem) on CodePen.

Cutting Holes

What if the part you want to cut out has holes in it? What if it shows parts of the background that you would like to exclude?

For instance, imagine you want to cut out a donut. Then you want the mask to exclude the hole in the middle. How do you then cut out the mask? The clip-path specification doesn’t allow more than one polygon unless we use SVGs. This means there is no possible way to create more than one shape at a time.

Well, one way to create these holes is to use very thin connectors and draw it as one shape. In other words, we can make a very thin incision from the edge and cut out the hole. This pen illustrates what it looks like when we make these connectors very thin:

See the Pen Cutting out images #7 by Mikael Ainalem (@ainalem) on CodePen.

Morphing Clip Paths

To make the highlight effect even more playful we can actually morph the clip-path itself. Below is an example of creating a dynamic highlight of a butterfly in three shots. The highlight is morphed between the three different cut-out parts on hover.

See the Pen Cutting out images #11 by Mikael Ainalem (@ainalem) on CodePen.

Double Exposure Effect

Another interesting effect we can create with clip-path is a double exposure. Here are two images blend in the same mask.

See the Pen Double exposure by Mikael Ainalem (@ainalem) on CodePen.

Browser support

So, can clip-path be used in all browsers? Unfortunately, not at the moment! If we look the caniuse table it kinda looks a bit like a traffic light at the time of this writing.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
66 51 54 No No TP*

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
11.0-11.2* 37* No 62 62 57

Wrapping it Up

Some key points I hope you walk away with from this post:

  • Using clipping paths is one way to make parts of your images stand out
  • Stacking the cut-out part on top of the original image makes it possible to create different kinds of highlight effects in images
  • We can leverage the browser’s hit testing on masks to create interactive effects on cut-out parts
  • The clip-path property makes way for UX patterns that highlight and create effects around parts of your images

Acknowledgments

  • Inkscape for vector image editing
  • Unsplash for the royalty-free images used in the examples
  • Github for the repository used for the conversion script
  • npm for being the package mnager for the conversion script
  • caniuse for browser support reference
  • CodePen for hosting the demos used in this post

Using CSS Clip Path to Create Interactive Effects is a post from CSS-Tricks

Secure Contexts Everywhere

Post pobrano z: Secure Contexts Everywhere

Anne van Kesteren for Mozilla says:

Effective immediately, all new features that are web-exposed are to be restricted to secure contexts. Web-exposed means that the feature is observable from a web page or server, whether through JavaScript, CSS, HTTP, media formats, etc. A feature can be anything from an extension of an existing IDL-defined object, a new CSS property, a new HTTP response header, to bigger features such as WebVR. In contrast, a new CSS color keyword would likely not be restricted to secure contexts.

In other words, if your site isn’t HTTPS, you won’t get new web tech features. Holy jeepers. The reasoning is the web should be using HTTPS, so this is our way of beating you with a stick if you try to use fancy features without going HTTPS first.

It’ll be fascinating to watch the first major feature drop and if they stick to their word here. The web dev forums of the internet will overflow with WHY DOESN’T grid-gap WORK WITH MY FLEXBOX? (or some likely coming-soon feature) questions and the answer will be: talk to your server team. What if they drop container queries behind this? That would be a hilarious devastating tornado of developer fury.

Direct Link to ArticlePermalink


Secure Contexts Everywhere is a post from CSS-Tricks

2017/2018 JavaScript

Post pobrano z: 2017/2018 JavaScript

There has been a lot of research on the landscape this year! Here are a few snippets from a bunch of articles. There is a ton of information in each, so I’m just picking out a few juicy quotes from each here.

Perhaps the most interesting bit is how different the data looked at is. Each of these is different: a big developer survey, npm data, GitHub data, and StackOverflow data. Yet, they mostly tell the same stories.

The Brutal Lifecycle of JavaScript Frameworks

Ian Allen of StackOverflow writes:

JavaScript UI frameworks and libraries work in cycles. Every six months or so, a new one pops up, claiming that it has revolutionized UI development. Thousands of developers adopt it into their new projects, blog posts are written, Stack Overflow questions are asked and answered, and then a newer (and even more revolutionary) framework pops up to usurp the throne.

Using the Stack Overflow Trends tool and some of our internal traffic data, we decided to take a look at some of the more prominent UI frameworks: Angular, React, Vue.js, Backbone, Knockout, and Ember.

Read More

The Top JavaScript Trends to Watch in 2018

Ryan Chartrand of X-Team for Hackernoon writes:

This time last year, not many had faith that Vue would ever become a big competitor to React when it comes to major companies adopting it, but it was impossible to ignore Vue this year, even sending Angular a bit into the shadows in terms of developer hype.

Read More

The State of JavaScript 2017

Sacha Greif uses a survey rather than usage data:

We asked over a hundred questions to more than 28,000 developers all over the world, covering topics going from front-end libraries all the way to back-end frameworks.

I particularly enjoyed the opinions. Lots of people who love working with JavaScript and find it to be moving in the right direction and find it overly complex.

Read More

The State of JavaScript Frameworks, 2017

This one is from Laurie Voss of npm, which is probably the best source of data for usage but faces interesting challenges with that data:

You can use npm’s download statistics to give you insight into the amount of people actively invested in using and maintaining a package. However, probably more important than absolute popularity is growth.

Packages, once incorporated into software, have very long lives. People very seldom rip packages out of software once they’re installed. Because of this very low “churn,” packages hardly ever decline in usage. Furthermore, nearly all packages in the npm Registry grow in usage as the number of total npm users continues to skyrocket. They vary only in how fast they’re growing.

This makes measuring growth harder, since measuring absolute growth in downloads all the time makes almost everything look popular.

All in all it tells a familiar story: React is incredibly popular and Vue is the one to watch.

Read More

Top JavaScript Libraries & Tech to Learn in 2018

Eric Elliott writes:

Vue.js did do very well in 2017. It got a lot of headlines and a lot of people got interested. As I predicted, it did not come close to unseating React, and I’m confident to predict it won’t unseat React in 2018, either. That said, it could overtake Angular in 2018.

Read More

2017 JavaScript Rising Stars

Michael Rambeau’s writes:

Once again, Vue.js is the trendiest project of the year, with more than 40,000 stars added on GitHub during the year.

It’s far more than in 2016 (26,000 stars), and the gap with the next contender (React) is even bigger.

Read More


2017/2018 JavaScript is a post from CSS-Tricks

Creating Vue.js Component Instances Programmatically

Post pobrano z: Creating Vue.js Component Instances Programmatically

This article assumes basic understanding of Vue.js framework and how to create components in it. If you are new to Vue, then this CSS-Tricks series is a good place to start.

I have been on a Vue.js project that required the ability to create components programmatically. By programmatically, I mean you create and insert the components completely from JavaScript, without writing anything in the template. This article aims to illustrate how different aspects of using components in a template, such as instantiation, props passing, slots, mounting, translate to JavaScript code.

Normally if you are working with the recommended Single File Component style, you would have a Button component like so:

<template>
 <button :class="type"><slot /></button>
</template>
<script>
 export default {
   name: 'Button',
   props: [ 'type' ],
 }
</script>

To use it in another component, all you have to do is import the Button component and insert its tag in the template:

<template>
 <Button type="primary">Click me!</Button>
</template>
<script>
 import Button from 'Button.vue'
 export default {
   name: 'App',
   components: { Button }
 }
</script>

In my case, I don’t know which component to insert in the template and also where to insert it. This information is only available at runtime. So I needed a way to dynamically create component instance for any passed component and insert it in the DOM, during runtime.

Creating the Instance

The very first idea I had to create a dynamic instance of a given component was to pass it to new and it would give me the actual instance. But if you notice carefully the script block in any of the above component code, they are all exporting a simple object, and not a class (constructor function). If I do this:

import Button from 'Button.vue'
var instance = new Button()

…it fails. We need a class. Or, in simple terms, a constructor function. The way to do that is to pass the component object to Vue.extend to create a subclass of the Vue constructor. Now we can create an instance out of it with the new keyword:

import Button from 'Button.vue'
import Vue from 'vue'
var ComponentClass = Vue.extend(Button)
var instance = new ComponentClass()

Hooray! Step 1 cleared! Now we need to insert it in the DOM.

Inserting in DOM

Every Vue instance has a method called $mount on it which mounts the component instance on the element you pass to it (i.e. it replaces the passed element with the component instance). This is not a behavior I wanted. I wanted to insert my component instances inside some DOM element. There is a way to do that too. From the official docs:

If elementOrSelector argument is not provided, the template will be rendered as an off-document element, and you will have to use native DOM API to insert it into the document yourself.

That’s what I did:

import Button from 'Button.vue'
import Vue from 'vue'
var ComponentClass = Vue.extend(Button)
var instance = new ComponentClass()
instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)

There are a couple of things to note in the code above.

First, $refs is the recommended way to get reference to a DOM element in Vue.js. You specify an attribute on the DOM element you want to reference (<div ref="container"></div> in this case) and then that element is available on the set key on component’s $refs property.

Second, to get the native DOM element reference from a Vue component instance, you can use the $el property.

Passing Props to the Instance

Next, I had to pass some props to my Button instance. Specifically, the type prop. The Vue constructor function accepts an options object that we can use to pass in and initialize related things. For passing props, there is a key called propsData which we can use, like so:

import Button from 'Button.vue'
import Vue from 'vue'
var ComponentClass = Vue.extend(Button)
var instance = new ComponentClass({
    propsData: { type: 'primary' }
})
instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)

We are almost done, with one final remaining bit. With the normal template method, we used button like: <Button>Click me!</Button>;. We simply wrote the inner text between the tags and it rendered inside the final button tag with the help of slot. But now how do we pass it?

Setting the Slot

If you have used slots in Vue.js, you might be aware that the slots are accessible on any instance on the $slots property. And if named slots are not used, then slots are available on $slots.default as an array. That is the exact key we’ll modify on the instance to set our button’s inner text. Remember, this needs to be done before mounting the instance. Note that in our case we just put a simple string in the slot because that is all we required. But you can pass more complex DOM to it in form for Virtual nodes or VNode using the createElement function. You can read about creating Virtual nodes in the Vue.js documentation. Thanks to a Vue core team member, Rahul, for suggesting this technique.

import Button from 'Button.vue'
import Vue from 'vue'
var ComponentClass = Vue.extend(Button)
var instance = new ComponentClass({
    propsData: { type: 'primary' }
})
instance.$slots.default = [ 'Click me!' ]
instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)

Final Demo

View Demo

Hope you liked this article. Follow me on Twitter where I share more articles and side projects of mine.


Creating Vue.js Component Instances Programmatically is a post from CSS-Tricks

Meet the New Dialog Element

Post pobrano z: Meet the New Dialog Element

Keith Grant discusses how HTML 5.2 has introduced a peculiar new element: <dialog>. This is an absolutely positioned and horizontally centered modal that appears on top of other content on a page. Keith looks at how to style this new element, the basic opening/closing functionality in JavaScript and, of course, the polyfills that we’ll need to get cross-browser support right.

Also, I had never heard of the ::backdrop pseudo element before. Thankfully the MDN documentation for this pseudo element digs into it a little bit more.

Direct Link to ArticlePermalink


Meet the New Dialog Element is a post from CSS-Tricks

Simplifying the Apple Watch Breathe App Animation With CSS Variables

Post pobrano z: Simplifying the Apple Watch Breathe App Animation With CSS Variables

When I saw the original article on how to recreate this animation, my first thought was that it could all be simplified with the use of preprocessors and especialy CSS variables. So let’s dive into it and see how!

Animated gif. Shows the result we want to get: six initially coinciding circles move out from the middle of the screen while the whole assembly scales up and rotates.
The result we want to reproduce.

The structure

We keep the exact same structure.

In order to avoid writing the same thing multiple times, I chose to use a preprocessor.

My choice of preprocessor always depends on what I want to do, as, in a lot of cases, something like Pug offers more flexibility, but other times, Haml or Slim allow me to write the least amount of code, without even having to introduce a loop variable I wouldn’t be needing later anyway.

Until recently, I would have probably used Haml in this case. However, I’m currently partial to another technique that lets me avoid setting the number of items both in the HTML and CSS preprocessor code, which means I avoid having to modify it in both if I need to use a different value at some point.

To better understand what I mean, consider the following Haml and Sass:

- 6.times do
  .item
$n: 6; // number of items

/* set styles depending on $n */

In the example above, if I change the number of items in the Haml code, then I need to also change it in the Sass code, otherwise things break. In a more or less obvious manner, the result is not the intended one anymore.

So we can go around that by setting the number of circles as the value of a CSS variable we later use in the Sass code. And, in this situation, I feel better using Pug:

- var nc = 6; // number of circles

.watch-face(style=`--nc: ${nc}`)
  - for(var i = 0; i < nc; i++)
    .circle(style=`--i: ${i}`)

We’ve also set the index for every .circle element in a similar manner.

The basic styles

We keep the exact same styles on the body, no change there.

Just like for the structure, we use a preprocessor in order to avoid writing almost the same thing multiple times. My choice is Sass because that’s what I’m most comfortable with, but for something simple like this demo, there’s nothing in particular about Sass that makes it the best choice – LESS or Stylus do the job just as well. It’s just faster for me to write Sass code, that’s all.

But what do we use a preprocessor for?

Well, first of all, we use a variable $d for the diameter of the circles, so that if we want to make them bigger or smaller and also control how far out they go during the animation, we only have to change the value of this variable.

In case anyone is wondering why not use CSS variables here, it’s because I prefer to only take this path when I need my variables to be dynamic. This is not the case with the diameter, so why write more and then maybe even have to come up with workarounds for CSS variable bugs we might run into?

$d: 8em;

.circle {
  width: $d; height: $d;
}

Note that we are not setting any dimensions on the wrapper (.watch-face). We don’t need to.

In general, if the purpose of an element is just to be a container for absolutely positioned elements, a container on which we apply group transforms (animated or not) and this container has no visible text content, no backgrounds, no borders, no box shadows… then there’s no need to set explicit dimensions on it.

A side effect of this is that, in order to keep our circles in the middle, we need to give them a negative margin of minus the radius (which is half the diameter).

$d: 8em;
$r: .5*$d;

.circle {
  margin: -$r;
  width: $d; height: $d;
}

We also give them the same border-radius, mix-blend-mode and background as in the original article and we get the following result:

Chrome screenshot. Shows the expected result we get at this point after applying these properties.
The expected result so far (live demo).

Well, we get the above in WebKit browsers and Firefox, as Edge doesn’t yet support mix-blend-mode (though you can vote for implementation and please do that if you want to see it supported because your votes do count), so it shows us something a bit ugly:

Edge screenshot. No mix-blend-mode support means the overlapping regions don't look any different from the non-overlapping ones and the result is uglyish.
The Edge result doesn’t look that good.

To get around this, we use @supports:

.circle {
  /* same styles as before */
  
  @supports not (mix-blend-mode: screen) {
    opacity: .75
  }
}

Not perfect, but much better:

Edge screenshot. Shows the result we get when we use partial transparency to get a result that's more like the mix-blend-mode one in other browsers.
Using @supports and opacity to fix the lack of mix-blend-mode support in Edge (live demo).

Now let’s look a bit at the result we want to get:

Screenshot of the desired circular distribution with annotations. The whole thing is split into two halves (a left one and a right one) by a vertical midline. The first three circles are in the right half and have a bluish green background, while the last three of the six circles are in the left half and have a yellowish green background. The circles are numbered starting from the topmost one in the right half and then they go clockwise.
The desired result.

We have six circles in total, three of them in the left half and three others in the right half. They all have a background that’s some kind of green, those in the left half a bit more towards yellow and those in the right half a bit more towards blue.

If we number our circles starting from the topmost one in the right half and then going clockwise, we have that the first three circles are in the right half and have a bluish green background and the last three are in the left half and have a yellowish green background.

At this point, we’ve set the background for all the circles to be the yellowish blue one. This means we need to override it for the first half of the six circles. Since we cannot use CSS variables in selectors, we do this from the Pug code:

- var nc = 6; // number of circles

style .circle:nth-child(-n + #{.5*nc}) { background: #529ca0 }
.watch-face(style=`--nc: ${nc}`)
  - for(var i = 0; i < nc; i++)
    .circle(style=`--i: ${i}`)

In case you need a refresher on this, :nth-child(-n + a) selects the items at the valid indices we get for n ≥ 0 integer values. In our case, a = .5*nc = .5*6 = 3, so our selector is :nth-child(-n + 3).

If we replace n with 0, we get 3, which is a valid index, so our selector matches the third circle.

If we replace n with 1, we get 2, also a valid index, so our selector matches the second circle.

If we replace n with 2, we get 1, again valid, so our selector matches the first circle.

If we replace n with 3, we get 0, which isn’t a valid index, as indices are not 0-based here. At this point, we stop as it becomes clear we won’t be getting any other positive values if we continue.

The following Pen illustrates how this works – the general rule is that :nth-child(-n + a) selects the first a items:

See the Pen by thebabydino (@thebabydino) on CodePen.

Returning to our circular distribution, the result so far can be seen below:

See the Pen by thebabydino (@thebabydino) on CodePen.

Positioning

First off, we make the wrapper relatively positioned and its .circle children absolutely positioned. Now they all overlap in the middle.

See the Pen by thebabydino (@thebabydino) on CodePen.

In order to understand what we need to do next, let’s take a look at the following illustration:

SVG Illustration. Shows the circles in their initial (overlapping dead in the middle) and final positions (with the rightmost one being highlighted in its final position). The segment between the central point of this circle in the initial position and in the final position is a horizontal segment of length equal to the circle radius.
The rightmost circle going from its initial to its final position (live).

The central points of the circles in the initial position are on the same horizontal line and a radius away from the rightmost circle. This means we can get to this final position by a translation of a radius $r along the x axis.

But what about the other circles? Their central points in the final position are also a radius away from their initial position, only along other lines.

SVG Illustration. Shows the circles in their initial (overlapping dead in the middle) and final positions. The segments connecting the initial position of their central points (all dead in the middle) and the final positions of the same points are highlighted. They're all segments of length equal to the circle radius.
All circles: initial position (dead in the middle) is a radius away from the final one for each and every one of them (live).

This means that, if we first rotate their system of coordinates until their x axis coincides with the line between the initial and final position of the central points and then translate them by a radius, we can get them all in the correct final position in a very similar manner.

See the Pen by thebabydino (@thebabydino) on CodePen.

Alright, but rotate each of them by what angle?

Well, we start from the fact that we have 360° on a circle around a point.

See the Pen by thebabydino (@thebabydino) on CodePen.

We have six circles distributed evenly, so the rotation difference between any two consecutive ones is 360°/6 = 60°. Since we don’t need to rotate the rightmost .circle (the second one), that one’s at , which puts the one before (the first one) at -60°, the one after (the second one) at 60° and so on.

See the Pen by thebabydino (@thebabydino) on CodePen.

Note that -60° and 300° = 360° - 60° occupy the same position on the circle, so whether we get there by a clockwise (positive) rotation of 300° or by going 60° the other way around the circle (which gives us the minus sign) doesn’t matter. We’ll be using the -60° option in the code because it makes it easier to spot a convenient pattern in our case.

So our transforms look like this:

.circle {
  &:nth-child(1 /* = 0 + 1 */) {
    transform: rotate(-60deg /* -1·60° = (0 - 1)·360°/6 */) translate($r);
  }
  &:nth-child(2 /* = 1 + 1 */) {
    transform: rotate(  0deg /*  0·60° = (1 - 1)·360°/6 */) translate($r);
  }
  &:nth-child(3 /* = 2 + 1 */) {
    transform: rotate( 60deg /*  1·60° = (2 - 1)·360°/6 */) translate($r);
  }
  &:nth-child(4 /* = 3 + 1 */) {
    transform: rotate(120deg /*  2·60° = (3 - 1)·360°/6 */) translate($r);
  }
  &:nth-child(5 /* = 4 + 1 */) {
    transform: rotate(180deg /*  3·60° = (4 - 1)·360°/6 */) translate($r);
  }
  &:nth-child(6 /* = 5 + 1 */) {
    transform: rotate(240deg /*  4·60° = (5 - 1)·360°/6 */) translate($r);
  }
}

This gives us the distribution we’ve been after:

See the Pen by thebabydino (@thebabydino) on CodePen.

However, it’s very repetitive code that can easily be compacted. For any of them, the rotation angle can be written as a function of the current index and the total number of items:

.circle {
  /* previous styles */
  
  transform: rotate(calc((var(--i) - 1)*360deg/var(--nc))) translate($r);
}

This works in WebKit browsers and Firefox 57+, but fails in Edge and older Firefox browsers due to the lack of support for using calc() inside rotate() functions.

Fortunately, in this case, we have the option of computing and setting the individual rotation angles in the Pug code and then using them as such in the Sass code:

- var nc = 6, ba = 360/nc;

style .circle:nth-child(-n + #{.5*nc}) { background: #529ca0 }
.watch-face
  - for(var i = 0; i < nc; i++)
    .circle(style=`--ca: ${(i - 1)*ba}deg`)
.circle {
  /* previous styles */
  
  transform: rotate(var(--ca)) translate($r);
}

We didn’t really need the previous custom properties for anything else in this case, so we just got rid of them.

We now have a compact code, cross-browser version of the distribution we’ve been after:

See the Pen by thebabydino (@thebabydino) on CodePen.

Good, this means we’re done with the most important part! Now for the fluff…

Finishing up

We take the transform declaration out of the class and put it inside a set of @keyframes. In the class, we replace it with the no translation case:

.circle {
  /* same as before */
  
  transform: rotate(var(--ca))
}

@keyframes circle {
  to { transform: rotate(var(--ca)) translate($r) }
}

We also add the @keyframes set for the pulsing animation on the .watch-face element.

@keyframes pulse {
  0% { transform: scale(.15) rotate(.5turn) }
}

Note that we don’t need both the 0% (from) and 100% (to) keyframes. Whenever these are missing, their values for the animated properties (just the transform property in our case) are generated from the values we’d have on the animated elements without the animation.

In the circle animation case, that’s rotate(var(--ca)). In the pulse animation case, scale(1) gives us the same matrix as none, which is the default value for transform so we don’t even need to set it on the .watch-face element.

We make the animation-duration a Sass variable, so that, if we ever want to change it, we only need to change it in one place. And finally, we set the animation property on both the .watch-face element and the .circle elements.

$t: 4s;

.watch-face {
  position: relative;
  animation: pulse $t cubic-bezier(.5, 0, .5, 1) infinite alternate
}

.circle {
  /* same as before */
  
  animation: circle $t infinite alternate
}

Note that we’re not setting a timing function for the circle animation. This is ease in the original demo and we don’t set it explicitly because it’s the default value.

And that’s it – we have our animated result!

We could also tweak the translation distance so that it’s not exactly $r, but a slightly smaller value (something like .95*$r for example). This can also make the mix-blend-mode effect a bit more interesting:

See the Pen by thebabydino (@thebabydino) on CodePen.

Bonus: the general case!

The above is for six .circle petals in particular. Now we’ll see how we can adapt it so that it works for any number of petals. Wait, do we need to do more than just change the number of circle elements from the Pug code?

Well, let’s see what happens if we do just that:

Screenshots. They show the result we get for nc equal to 6, 8 and 9. When nc is 6, we have the previous case: splitting the whole thing into two halves with a vertical line, we have the first three (bluish green) circles in the right half and the last three (yellowish green) circles in the left half. When nc is 8, we also have the first half of the circles (the first four, bluish green) on one side of a line splitting the assembly into two geometrically symmetrical halves and the last four circles (yellowish green) on the other side of the same line. This line however isn't vertical anymore. In the nc = 9 case, all circles are yellowish green.
The result for nc equal to 6 (left), 8 (middle) and 9 (right).

The results don’t look bad, but they don’t fully follow the same pattern – having the first half of the circles (the bluish green ones) on the right side of a vertical symmetry line and the second half (yellowish green) on the left side.

We’re pretty close in the nc = 8 case, but the symmetry line isn’t vertical. In the nc = 9 case however, all our circles have a yellowish green background.

So let’s see why these things happen and how we can get the results we actually want.

Making :nth-child() work for us

First off, remember we’re making half the number of circles have a bluish green background with this little bit of code:

.circle:nth-child(-n + #{.5*nc}) { background: #529ca0 }

But in the nc = 9 case, we have that .5*nc = .5*9 = 4.5, which makes our selector :nth-child(-n + 4.5). Since 4.5 is not an integer, the selector isn’t valid and the background doesn’t get applied. So the first thing we do here is floor the .5*nc value:

style .circle:nth-child(-n + #{~~(.5*nc)}) { background: #529ca0 }

This is better, as for a nc value of 9, the selector we get is .circle:nth-child(-n + 4), which gets us the first 4 items to apply a bluish green background on them:

See the Pen by thebabydino (@thebabydino) on CodePen.

However, we still don’t have the same number of bluish green and yellowish green circles if nc is odd. In order to fix that, we make the circle in the middle (going from the first to the last) have a gradient background.

By „the circle in the middle” we mean the circle that’s an equal number of circles away from both the start and the end. The following interactive demo illustrates this, as well as the fact that, when the total number of circles is even, we don’t have a middle circle.

See the Pen by thebabydino (@thebabydino) on CodePen.

Alright, how do we get this circle?

Mathematically, this is the intersection between the set containing the first ceil(.5*nc) items and the set containing all but the first floor(.5*nc) items. If nc is even, then floor(.5*nc) and ceil(.5*nc) are equal and our intersection is the empty set . This is illustrated by the following Pen:

See the Pen by thebabydino (@thebabydino) on CodePen.

We get the first ceil(.5*nc) items using :nth-child(-n + #{Math.ceil(.5*nc)}), but what about the other set?

In general, :nth-child(n + a) selects all but the first a - 1 items:

See the Pen by thebabydino (@thebabydino) on CodePen.

So in order to get all but the first floor(.5*nc) items, we use :nth-child(n + #{~~(.5*nc) + 1}).

This means we have the following selector for the middle circle:

:nth-child(n + #{~~(.5*nc) + 1}):nth-child(-n + #{Math.ceil(.5*nc)})

Let’s see what this gives us.

  • If we have 3 items, our selector is :nth-child(n + 2):nth-child(-n + 2), which gets us the second item (the intersection between the {2, 3, 4, ...} and {2, 1} sets)
  • If we have 4 items, our selector is :nth-child(n + 3):nth-child(-n + 2), which doesn’t catch anything (the intersection between the {3, 4, 5, ...} and {2, 1} sets is the empty set )
  • If we have 5 items, our selector is :nth-child(n + 3):nth-child(-n + 3), which gets us the third item (the intersection between the {3, 4, 5, ...} and {3, 2, 1} sets)
  • If we have 6 items, our selector is :nth-child(n + 4):nth-child(-n + 3), which doesn’t catch anything (the intersection between the {4, 5, 6, ...} and {3, 2, 1} sets is the empty set )
  • If we have 7 items, our selector is :nth-child(n + 4):nth-child(-n + 4), which gets us the fourth item (the intersection between the {4, 5, 6, ...} and {4, 3, 2, 1} sets)
  • If we have 8 items, our selector is :nth-child(n + 5):nth-child(-n + 4), which doesn’t catch anything (the intersection between the {5, 6, 7, ...} and {4, 3, 2, 1} sets is the empty set )
  • If we have 9 items, our selector is :nth-child(n + 5):nth-child(-n + 5), which gets us the fifth item (the intersection between the {5, 6, 7, ...} and {5, 4, 3, 2, 1} sets)

Now that we can select the item in the middle when we have an odd number of them in total, let’s give it a gradient background:

- var nc = 6, ba = 360/nc;

style .circle:nth-child(-n + #{~~(.5*nc)}) { background: var(--c0) }
  | .circle:nth-child(n + #{~~(.5*nc) + 1}):nth-child(-n + #{Math.ceil(.5*nc)}) {
  |   background: linear-gradient(var(--c0), var(--c1))
  | }
.watch-face(style=`--c0: #529ca0; --c1: #61bea2`)
  - for(var i = 0; i < nc; i++)
    .circle(style=`--ca: ${(i - 1)*ba}deg`)

The reason why we use a top to bottom gradient is that, ultimately, we want this item to be at the bottom, split into two halves by the vertical symmetry line of the assembly. This means we first need to rotate it until its x axis points down and then translate it down along this new direction of its x axis. In this position, the top of the item is in the right half of the assembly and the bottom of the item is in the left half of the assembly. So, if we want a gradient from the right side of the assembly to the left side of the assembly, this is a top to bottom gradient on that actual .circle element.

See the Pen by thebabydino (@thebabydino) on CodePen.

Using this technique, we have now solved the issue of the backgrounds for the general case:

See the Pen by thebabydino (@thebabydino) on CodePen.

Now all that’s left to do is make the symmetry axis vertical.

Taming the angles

In order to see what we need to do here, let’s focus on the desired positioning in the top part. There, we want to always have two circles (the first in DOM order on the right and the last in DOM order on the left) symmetrically positioned with respect to the vertical axis that splits our assembly into two halves that mirror each other.

See the Pen by thebabydino (@thebabydino) on CodePen.

The fact that they’re symmetrical means the vertical axis splits the angular distance between them ba (which is 360° divided by the total number of circles nc) into two equal halves.

SVG Illustration. Shows the circles distributed around a central point with the two at the top (symmetrical with respect to the vertical axis that splits the whole assembly into two mirrored halves) being highlighted. This middle axis splits the angular distance between the central points of these two circles into two equal halves.
Angles formed by vertical symmetry line and the radial lines to the central points of the top angles are both equal to half a base angle (live).

So both are half a base angle (where the base angle ba is 360° divided by the total number of circles nc) away from the vertical symmetry axis, one in the clockwise direction and the other one the other way.

The upper half of the symmetry axis is at -90° (which is equivalent to 270°).

SVG Illustration. Shows degrees around a circle in 90° steps. We start from the right (3 o'clock). This is the 0° and, in general, any multiple of 360° angle. Going clockwise, we have 90° down (at 6 o'clock), 180° on the left (at 9 o'clock) and 270° at the top (12 o'clock). Going the other way from 0°, we have -90° at the top (12 o'clock), -180° on the left (9 o'clock) and so on.
Degree values around the circle (live).

So in order to get to the first circle in DOM order (the one at the top on the right), we start from , go by 90° in the negative direction and then by half a base angle back in the positive direction (clockwise). This puts the first circle at .5*ba - 90 degrees.

SVG Illustration. Shows graphically how to get the angular position of the first circle. Starting from 0° (3 o'clock), we go in the negative direction by 90° (getting at 12 o'clock). Afterwards, we go back in the positive direction by half a base angle.
How to get the angle the first circle is placed at (live).

After that, every other circle is at the angle of the previous circle plus a base angle. This way, we have:

  • the first circle (index 0, selector :nth-child(1)) is at ca₀ = .5*ba - 90 degrees
  • the second circle (index 1, selector :nth-child(2)) is at ca₁ = ca₀ + ba = ca₀ + 1*ba degrees
  • the third circle (index 2, selector :nth-child(3)u) is at ca₂ = ca₁ + ba = ca₀ + ba + ba = ca₀ + 2*ba degrees
  • in general, the circle of index k is at caₖ = caₖ₋₁ + ba = ca₀ + k*ba degrees

So the the current angle of the circle at index i is .5*ba - 90 + i*ba = (i + .5)*ba - 90 degrees:

- var nc = 6, ba = 360/nc;

//- same as before
.watch-face(style=`--c0: #529ca0; --c1: #61bea2`)
  - for(var i = 0; i < nc; i++)
    .circle(style=`--ca: ${(i + .5)*ba - 90}deg`)

This gives our final Pen, where we only need to change nc from the Pug code to change the result:

See the Pen by thebabydino (@thebabydino) on CodePen.


Simplifying the Apple Watch Breathe App Animation With CSS Variables is a post from CSS-Tricks

“Stop Using CSS Selectors for Non-CSS”

Post pobrano z: “Stop Using CSS Selectors for Non-CSS”

I saw Nicole Dominguez tweet this the other day:

say it louder for the people in the backhttps://t.co/prDKo5QaZi

— nicole (@sodevious) January 11, 2018

I wasn’t at this conference, so I have very little context. Normally, I’d consider it a sin to weigh in on a subject brought up by looking at two out-of-context slides, but I’m only weighing in out of interest and to continue the conversation.

The idea seems to be that if you need to select an element in the DOM with JavaScript, don’t use the same selector as you would in CSS.

So if you have…

<article class="article">
</article>

…and you need to apply an event listener to that article for some reason, then don’t use…

$(".article")

(or querySelector or whatever, I assume.)

Instead, apply an attribute intended just for the JavaScript to target, like…

<article class="article" data-hoverable>
</article>

…and target that like…

$("[data-hoverable]")

The idea is that you can separate jobs. The class has the job of styling, and the data attribute has the job of JavaScripting. Both can change without affecting each other.

Seems reasonable to me.

Also seems like there is plenty to talk about here. Performance, I suppose, but that’s probably the least-interesting thing since selectors are generally pretty damn fast these days. We could continue the conversation by talking about:

  • What naming convention?
  • Should you be naming events?
  • What if it needs to be selected for different reasons multiple times?
  • Can you or should you use IDs?
  • Is it worth avoiding DOM selection at all if you can?
  • What other nuances are part of this discussion?

I saw Michael Scharnagl had some thoughts on his own usage of ID’s, classes, and data-attributes that could help frame things a bit.


“Stop Using CSS Selectors for Non-CSS” is a post from CSS-Tricks

Creating a Vue.js Serverless Checkout Form: Setup and Testing

Post pobrano z: Creating a Vue.js Serverless Checkout Form: Setup and Testing

There comes a time in any young app’s life when it will have to monetize. There are a number of ways to become profitable, but accepting cash is a surefire way to make this more direct. In this four-part tutorial, we’ll go over how to set up a serverless function, make it talk to the Stripe API, and connect it to a checkout form that is setup as a Vue application. This may sound daunting, but it’s actually pretty straightforward! Let’s dig in.

Vue shop

Article Series:

  1. Setup and Testing (This Post)
  2. Stripe Function and Hosting (Coming Soon)
  3. Application and Checkout Component (Coming Soon)
  4. Configure the Checkout Component (Coming Soon)

What is Serverless?

We’ve covered serverless concepts before but, in case you haven’t read that article, let’s talk for a minute about what we mean by „serverless” because it’s a bit of a misnomer.

The promise of serverless is to spend less time setting up and maintaining a server. You’re essentially letting the service handle maintenance and scaling for you, and you boil what you need down to functions that run certain code when a request is made. For this reason, people may refer to this as FaaS. This is really useful because you pay for what you use, rather than a large container that you might not need in its entirety. You also primarily hunker down and focus just on the code you need to run instead of babysitting a server, which really appeals to a lot of people who’d like to get up and running quickly.

But FaaS isn’t always the right tool for the job. It’s really useful for small executions but, if you have processes that might hold up resources or a ton of computation, being able to communicate with a server as you normally do might be more efficient.

What we’re going to make is a perfect use case for going serverless. Stripe checkouts are pretty seamless to integrate on both the client and server side, but we do actually need to execute some logic on the server, so we’ll use Azure to help us with this. The portal and Github integration are pretty quick to manipulate, as long as you know where to go. So by all means, let’s make it happen!

Sign up for Stripe

First, we’ll create a Stripe account. We verify our new account via email and then we’ll head over to the API section, where we can retrieve two keys. You’ll note that we’re in test mode right now, which is good! We’ll keep it like that for testing, and unveil the testing key token to use while we set up the application.

Once you’re signed in, go to the API section of your dashboard to retrieve your key.

Stripe testing dashboard
The Stripe API screen

You may also want to add a phone number to your account for 2 factor auth as well.

Setting up Our Serverless Function in the Azure Portal

First, we’ll head over to the portal, (or if you don’t already have an account, you can sign up for a free trial here) and select New > Serverless Function

New Function
Setting up a new Servless Function in Azure

When we click on the Serverless Function app, we’ll be taken to a panel that asks for details to help with the setup. As you can see in the screenshot above, it will autofill most of the fields just from the app name, but let’s go over some of these options quickly:

  • Add in a unique name
  • A Resource Group (if you don’t already have one, create one)
  • I use the Windows OS because the Linux is still in preview, so Windows will be more stable
  • I use the Consumption Plan because this is the one that will have payments that scale with the use, and it will also scale automatically. The other option, App Service Plan, is good for people who prefer everything to be a bit more manual.
  • Choose a location that is close to your customer base, or a midpoint between two customer bases
  • Choose a storage, or create one as I’ve done
  • I’ll also check Pin to Dashboard because I want to be able to retrieve my function quickly later
New function settings

This will bring you back to the main portal dashboard and let you know that your function is deploying. Once it’s done, it take you to a main screen that has all of your options. From here, we’ll want to create our function, and it will be an HTTP trigger.

We’ll select Functions under our function name, and you’ll see a little table with a plus that says “New Function”:

New Function in the Portal

Once we click here, we have a few options on what we can create. We’ll pick HTTP Trigger:

Choose HTTP Trigger

We’ll be able to select the language (pick „JavaScript”) and then „Create”:

Pick the Language and Create

The Default Testing Function

From here, we’re given a default testing function which helps us see how this all works. If we open all of these panels and hit the Run button, we’ll see the output in logs.

The initial testing output
Running the function in a test environment

Here’s the code we were given:

module.exports = function(context, req) {
  context.log('JavaScript HTTP trigger function processed a request.');

  if (req.query.name || (req.body && req.body.name)) {
    context.res = {
      // status: 200, /* Defaults to 200 */
      body: 'Hello ' + (req.query.name || req.body.name)
    };
  } else {
    context.res = {
      status: 400,
      body: 'Please pass a name on the query string or in the request body'
    };
  }
  context.done();
};

You’ll see here that we’re passing in the context. That allows us to log, which will be shown in the lowest panel below. In the Test panel on the right, we can pass in a request body that can be used to test our application. When it runs, we see the output with a 200 status and know that everything is working. We also have a context.log for the case that it gives us a 400 error. If you’d like to play around with a serverless function and see it in action for yourself, you can create one with a free trial account.

Next Up…

Now that we have the base of our serverless function, let’s set up what we’ll need to communicate with Stripe! More to come in the next post in this series.

Article Series:

  1. Setup and Testing (This Post)
  2. Stripe Function and Hosting (Coming Soon)
  3. Application and Checkout Component (Coming Soon)
  4. Configure the Checkout Component (Coming Soon)

Creating a Vue.js Serverless Checkout Form: Setup and Testing is a post from CSS-Tricks

New flexbox guides on MDN

Post pobrano z: New flexbox guides on MDN

MDN released a comprehensive guide to Flexbox with new and updated materials by Rachel Andrew. The guide includes 11 posts demonstrating layouts, use cases and everything you could possibly want or need to know on the topic. All of the related Flexbox properties are nicely and conveniently attached to the table of contents, making this extremely easy to use.

In this post, Rachel adds helpful thoughts and context about Flexbox. Her comment on Flexbox initially being treated as a silver bullet solution for all our layout issues struck me:

Prior to Grid shipping, Flexbox was seen as the spec to solve all of our layout problems, yet a lot of the difficulty in using Flexbox is when we try to use it to create the kind of two-dimensional layouts that Grid is designed for. Once again, we find ourselves fighting to persuade a layout method to do things it wasn’t designed to do.

Guilty as charged. I remember being so eager to ditch floats and learn a new syntax that I treated Flexbox as a square peg trying to be fit into a round hole. That definitely bit me on at least one project.

Most importantly about this guide is that it forms a sort of trifecta of reference materials on layout specifications provided by CSS: Flexbox, Grid and other Box Alignment properties.

Oh, and while we’re on the topic, we have Flexbox and Grid guides right here on CSS-Tricks. You can never learn too much, right?

Direct Link to ArticlePermalink


New flexbox guides on MDN is a post from CSS-Tricks

Third-Party Scripts

Post pobrano z: Third-Party Scripts

Trent Walton:

My latest realization is that delivering a performant, accessible, responsive, scalable website isn’t enough: I also need to consider the impact of third-party scripts. No matter how solid I think my prototype is, it doesn’t absolve me from paying attention to what happens during implementation, specifically when it comes to the addition of these third-party scripts.

I recently had a conversation with a friend working on quite a high profile e-commerce site. They were hired to develop the site, but particularly with performance in mind. They were going the PWA route, but were immediately hamstrung by third-party scripts. One of them, apparently unavoidably, couldn’t be HTTPS, meaning the site was immediately disqualified from being a PWA. They could still do a good job in many other areas, but right and left their great performance work was slaughtered by third-party scripts. I don’t envy being in that position.

It’s often the fault of „tag managers.” There are a bunch of them out there. Here’s a marketing pitch for one of them:

Marketers want tag management that’s simple, reliable, and integrates easily with existing systems … You’ll launch programs faster, so you can make swifter decisions.

In other words, „Give your marketing team the ability to add whatever third-party JavaScript they want quickly without having to go through your normal deployment process.” I can understand why they are needed in some organizations, but it still sends chills up my spine.

Third-party scripts could conceivably be a part of a design style guide. Right alongside your buttons and modals could be a list of the third-party scripts in place on a site. Brad Frost:

The idea is that someone (or as Trent points out, some *thing*) could hypothetically crawl through all the included scripts on a site, and display them in the in style guide alongside all the color swatches, icons, UI components, etc. After all, they affect the end user experience just as much (if not more) than all those other design elements. You can visually weight them based on how gnarly they are and thus have thoughtful conversations with your team — especially those folks are carelessly chucking in all these performance-damning scripts — about the pros and cons of each script that gets included.

Third-party scripts are probably the #1 cause of poor performance and bad UX on the web. It’s no wonder things like AMP exist. The fact that it disallows third-party scripts is probably the largest contributor to it making sites fast. Controversial as hell, though, in its other choices.

As fate would have it, third-party JavaScript is even more dangerous than it ever has been, thanks to Spectre and Meltdown. Jorgé:

Q: Is JavaScript vulnerable in my browser?
A: Yes, browsing a web can give access to third parties to your machine’s memory beyond the browser.

😳

More on Third-Party JavaScript

If you, like Trent, are planning to bone up on your third-party JavaScript chops, here’s a bunch of stuff from other developers in the past few years digging into it all. Some of this is targeted at you being the deliverer of the third-party JavaScript.

Third Party JavaScript (In the Third Person) Slides by Alex Sexton

Presentation slide

View Presentation


On Third-Party Javascript – The Principles by Gergely Nemeth

When serving third-party JavaScript applications the size of it and the cache policy are crucial, as both not just affect the time your users have to wait to see the application, but also your monthly bills.

See also: Writing third-party Javascript the integration part in a nutshell.

Read Post


Third-Party Javascript by Ben Vinegar and Anton Kovalyov


Things to Know (and Potential Dangers) with Third-Party Scripts by Yaphi Berhanu

The web is full of third-party scripts. Sites use them for ads, analytics, retargeting, and more. But this isn’t always the whole story. Scripts can track your behavior, your preferences, and other information.

Read Post


I’m harvesting credit card numbers and passwords from your site. Here’s how. by David Gilbertson

My goal is simply to point out that any site that includes third party code is alarmingly vulnerable, in a completely undetectable way.

Read Post


Ain’t No Party Like A Third-Party JS Party by Rebecca Murphey

You thought you had the hang of this whole JavaScript thing, but now you’re in the world of third-party JavaScript, where all you control is a single script tag and where it’s all but impossible to dream up every hostile environment in which your code will be expected to work. „It works on my machine” has never rung quite so hollow. In this talk, we’ll take a look at some of the delightful bugs we’ve had to solve at Bazaarvoice while working on the third-party JavaScript app that collects and displays ratings and reviews for some of the world’s largest retailers.

Watch Video

(Subscription required)


3rd Party Javascript Management Cheat Sheet

The invocation of 3rd party JS code in a web application requires consideration for 3 risks in particular:

  1. The loss of control over changes to the client application,
  2. The execution of arbitrary code on client systems,
  3. The disclosure or leakage of sensitive information to 3rd parties.

Read Post


Third-Party Scripts is a post from CSS-Tricks