slide_icon

 

WELCOME TO   MY BLOG

You can see my thought and can share your thought here.

Ekta Bhargava
An Intro to Monkey Testing with Gremlins.js

An Intro to Monkey Testing with Gremlins.js

A common idiom in our industry is, "You never can predict how the user will use your product once they get it in their hands." If you've ever watched a stakeholder use a website or web application for the first time, you may know this firsthand. I can't count the number of times I've seen a user seemingly forget how to use websites on a mobile device, or try to use it in a way that makes you think, "But no one would actually do that in real life!" The thing is, you never really do know what a user may do in the moment. They might be in a frantic state of mind, trying to accomplish something too quickly, and don't tap or type the way a calm, focused user might. This fits right into the all-too-common scenario of designing and developing for the best case scenario, and not thinking about edge cases or "what happens if things don't happen perfectly in this order?" As developers, we tend to build things thinking that everything will be understood, that the user is rational and should just know that tapping around too quickly might cause something weird to happen. It can even affect those who might make accidental taps or clicks when not giving an app full attention - how many times have you accidentally tapped on a mobile device when you were walking and talking while also trying to reply to a tweet or email. Building out tools to help us test the unpredictable aren't entirely new. In 2012, Netflix had open-sourced their internal service Chaos Monkey, which "terminates virtual machine instances and containers that run inside of your production environment." In plain language, it's a service that tears down servers at random to ensure an entire system doesn't violently collapse during a failure. Our development communities also remind us to not just design for "the happy path", but how can we actually detect for unpredicted points of failure in our interfaces the way we can with our server architectures? If a hundred monkeys at typewriters can write the works of Shakespeare, then one monkey should surely be able to find bugs and problems in our interfaces. Bring in the monkeys Monkey testing is a method of testing that generates random user input - clicks, swipes, entering input - with the sole purpose of finding issues with, or entirely breaking, your application. Unlike unit and acceptance testing, where you are writing test cases that occur in a specific order or set of conditions, which ultimately creates bias in how your interface is tested. Developers have less control over how a monkey test will execute, and since they are random every time they are run, you'll never be testing for just one scenario, but rather an infinite combination of interactions. Although this type of testing is available for most technology stacks, things built for the web haven't necessarily got there yet. For example, the Android SDK has a UI Exerciser Monkey that handles most interface-level and system-level events. As web developers have begun to think more critically about performance and stress testing, some of these ideas have finally made it over to the world of the web in the form of Gremlins.js, a JavaScript-based monkey testing library written by the team at Marmelab. Monkeys, Gremlins, And Other Fun Critters Gremlins.js runs with as little or as much control as you could need. It has a fairly low time cost for initial setup. There are three ways to start using Gremlins.js. Standalone library The easiest way to incorporate the library is to include the library directly into your site. This will put gremlins into your project's global namespace, meaning that you can access it from anywhere within your project. <script src="path/to/gremlins.min.js"></script> <script type="javascript"> // You can also run this in any file now! gremlins.createHorde().unleash(); </script> Require.js module If you are using Require.js in your project, you can import Gremlins.js in a non-global, as-needed fashion. require.config({ paths: { gremlins: 'scripts/libraries/gremlins.min' } }); require(['gremlins'], function(gremlins) { gremlins.createHorde().unleash(); }); Bookmarklet If you prefer to use monkey testing in a ad hoc manner, there's even a bookmarklet that allows one-click testing on whichever page you are on. You can grab the bookmarklet from the installation instructions. Monkeying Around If you've opted for direct inclusion of the library or importing it through Require, you can now start playing around with Gremlins on our own! In our installation examples, we call gremlins.createHorde().unleash() - so what is this doing? gremlins // Yo, Gremlins .createHorde() // Create me a default horde .unleash(); // Then immediately release them See the Pen Gremlins.js out of the box by Alicia Sedlock (@aliciasedlock) on CodePen. The default horde includes all five available types of randomly generated user interactions, otherwise known as "species of gremlins", that include: formFillerGremlin fills in inputs with data, clicks checkboxes/radio buttons, and interacts with other standard form elements clickerGremlin clicks anywhere on the visible document toucherGremlin touches anywhere on the visible document scrollerGremlin scrolls the viewport typerGremlin triggers random typing on a simulated keyboard When triggered, gremlins will leave a visual indication on the screen for the action that was performed. They will also leave a log of the actions they took, found in the developer console, along with any additional data associated with that species. They'll look something like the example below. gremlin formFiller input 5 in <input type=​"number" name=​"age">​ gremlin formFiller input pzdoyzshh0k9@o8cpskdb73nmi.r7r in <input type=​"email" name=​"email">​ gremlin clicker click at 1219 301 gremlin scroller scroll to 100 25 By default, gremlins will be randomly triggered in 10 millisecond intervals for a total of 1000 times. Alongside our "bad" gremlins who like to cause trouble, there are also helpful gremlins, called mogwais, available to us. They don't interfere with our application like gremlins, and instead mostly do reporting on how our application is holding up, such as logging the current frame rate. Mogwais will throw errors if the frame rate drops below 10. mogwai fps 12.67 mogwai fps 23.56 err > mogwai fps 7.54 < err mogwai fps 15.76 The combination of gremlin and mogwai logging provides a great picture of everything that's happened over the course of the test. Without much of any customization at all, Gremlins.js gives us a pretty robust test right out of the box. Advanced Monkeying Around If after using the default configuration, you have needs not being met, there are a fair number of ways to customize the way things run. For example, perhaps you want to only focus on particular components on a page at a time, rather than always testing a page in its entirety. Though we can't scope all species of gremlins, we can limit toucher, clicker, and formFiller to scope certain areas of our page at a given time. Specifically, we ask a gremlin to check the parent of an element it attempts to target. If that element is within our scope, the gremlin will proceed with the action. Otherwise, the gremlin will reattempt to find an element to interact with. We can also tell the gremlin how many times we want them to try to attempt the action before giving up with maxNbTries. gremlins.species.clicker().canClick(function(element) { return $(element).parents('.my-component').length; /** Is the element this gremlin attempted to click within our wanted scope? Let it proceed by returning true! Otherwise, tell it to try again by returning false. **/ }).maxNbTries(5); // Our gremlin will tolerate 5 false returns for canClick before it gives up and moves on // Similarly, we can control the scope of formFiller and toucher. gremlins.species.formFiller.canFillElement(/** do stuff here **/); gremlins.species.toucher.canTouch(/** do stuff here **/); See the Pen Gremlins.js out of the box by Alicia Sedlock (@aliciasedlock) on CodePen. Custom Gremlins If you're feeling limited by the selection of gremlin species at your disposal, fear not! You can write your own custom gremlins to perform any other actions you may be expecting users to make. For example, do you want to check what happens if a user attempts to submit a form randomly at any given part of their experience? You can hope that clicker will randomly click on our submit button, or you can create a custom submission gremlin to increase our chances, as well as control of how it's executed. This requires a bit of understanding of how to create and customize DOM events in JavaScript, so let's walk through the pieces involved in making a submission gremlin. gremlins.createHorde() // first, create our horde .allGremlins() // and enable all gremlins .gremlin(function() { // Now let's define our submission gremlin var targetElement, availableForms; availableForms = document.querySelectorAll('form'); // Let's get all available form elements on the page targetElement = availableForms[Math.floor(Math.random()*availableForms.length)]; // Then let's grab a random element from those results // Now, we create a dummy submission event var evt = document.createEvent('HTMLEvents'); // Create an event container evt.initEvent('submit'); // Define our event as a submit event targetElement.dispatchEvent(evt); // Finally, dispatch the submit event onto our randomly selected form // We also want to make sure to log this event like others gremlins do! console.log('gremlin submit ', targetElement); }) .unleash(); See the Pen Customized gremlin with Gremlins.js by Alicia Sedlock (@aliciasedlock) on CodePen. If you're looking for more guidance on creating custom events, checkout Mozilla Developer Network's documentation on creating events, and definitely check out the source of how Gremlins.js creates its events (the clicker gremlin is a great place to start) Seeding Hordes Having a brand new horde execute every time you run this kind of test will help stress test your UI in a lot of different scenarios. However, if you unleash a horde, and end up with errors, how are you really supposed to know if you've fixed the issues that caused those errors? For cases where you want to run the same horde multiple times, you can choose to seed the horde. This will give you the exact same horde every time you execute the test. var horde = gremlins.createHorde(); horde.seed(1234); horde.unleash(); You may want to weigh how often you uses seeded hordes versus randomized hordes in a long term solution. While seeded hordes allow for retesting, much of the benefit of monkey testing lies in its randomness, which becomes somewhat moot in a scenario where the same seed is always used. Conclusion The web community often talks about not making assumptions about our users. They may have slow connections, not-the-latest device line, or be impaired in a way that requires the sit their using to be accessible. We also can't promise that five-year-old Jaime doesn't grab their parent's phone, start wildly tapping, and end up causing major issues with whatever thing they were using. Or Kassidy from marketing, after getting their hands on the product for the first time, feverishly clicking or tapping away in excitement. The order, speed, or repetition of any user action can't be predicted. As developers, we owe it to our users to make sure that our services don't become unexpectedly broken simply from expecting them to only take happy path actions. The choices for client-side monkey testing are slim, but Gremlins.js gets the fundamentals down right out of the gate. As with any type of testing library or framework, we can only improve upon it if people use it! They are actively seeking contributors, so if you have a wishlist for things this library can do, let them know! An Intro to Monkey Testing with Gremlins.js is a post from CSS-Tricks

Bliki: ValueObject

Bliki: ValueObject

When programming, I often find it's useful to represent things as a compound. A 2D coordinate consists of an x value and y value. An amount of money consists of a number and a currency. A date range consists of start and end dates, which themselves can be compounds of year, month, and day. As I do this, I run into the question of whether two compound objects are the same. If I have two point objects that both represent the Cartesian coordinates of (2,3), it makes sense to treat them as equal. Objects that are equal due to the value of their properties, in this case their x and y coordinates, are called value objects. But unless I'm careful when programming, I may not get that behavior in my programs Say I want to represent a point in JavaScript. const p1 = {x: 2, y: 3}; const p2 = {x: 2, y: 3}; assert.notEqual(p1,p2); // NOT what I want Sadly that test passes. It does so because JavaScript tests equality for js objects by looking at their references, ignoring the values they contain. In many situations using references rather than values makes sense. If I'm loading and manipulating a bunch of sales orders, it makes sense to load each order into a single place. If I then need to see if the Alice's latest order is in the next delivery, I can take the memory reference, or identity, of Alice's order and see if that reference is in the list of orders in the delivery. For this test, I don't have to worry about what's in the order. Similarly I might rely on a unique order number, testing to see if Alice's order number is on the delivery list. Therefore I find it useful to think of two classes of object: value objects and reference objects, depending on how I tell them apart [1]. I need to ensure that I know how I expect each object to handle equality and to program them so they behave according to my expectations. How I do that depends on the programming language I'm working in. Some languages treat all compound data as values. If I make a simple compound in Clojure, it looks like this. > (= {:x 2, :y 3} {:x 2, :y 3}) true That's the functional style - treating everything as immutable values. But if I'm not in a functional language, I can still often create value objects. In Java for example, the default point class behaves how I'd like. assertEquals(new Point(2, 3), new Point(2, 3)); // Java The way this works is that the point class overrides the default equals method with the tests for the values. [2] [3] I can do something similar in JavaScript. class Point { constructor(x, y) { this.x = x; this.y = y; } equals (other) { return this.x === other.x && this.y === other.y; } } const p1 = new Point(2,3); const p2 = new Point(2,3); assert(p1.equals(p2)); The problem with JavaScript here is that this equals method I defined is a mystery to any other JavaScript library. const somePoints = [new Point(2,3)]; const p = new Point(2,3); assert.isFalse(somePoints.includes(p)); // not what I want //so I have to do this assert(somePoints.some(i => i.equals(p))); This isn't an issue in Java because Object.equals is defined in the core library and all other libraries use it for comparisons (== is usually used only for primitives). One of the nice consequences of value objects is that I don't need to care about whether I have a reference to the same object in memory or a different reference with an equal value. However if I'm not careful that happy ignorance can lead to a problem, which I'll illustrate with a bit of Java. Date retirementDate = new Date(Date.parse("Tue 1 Nov 2016")); // this means we need a retirement party Date partyDate = retirementDate; // but that date is a Tuesday, let's party on the weekend partyDate.setDate(5); assertEquals(new Date(Date.parse("Sat 5 Nov 2016")), retirementDate); // oops, now I have to work three more days :-( This is an example of an Aliasing Bug, I change a date in one place and it has consequences beyond what I expected [4]. To avoid aliasing bugs I follow a simple but important rule: value objects should be immutable. If I want to change my party date, I create a new object instead. Date retirementDate = new Date(Date.parse("Tue 1 Nov 2016")); Date partyDate = retirementDate; // treat date as immutable partyDate = new Date(Date.parse("Sat 5 Nov 2016")); // and I still retire on Tuesday assertEquals(new Date(Date.parse("Tue 1 Nov 2016")), retirementDate); Of course, it makes it much easier to treat value objects as immutable if they really are immutable. With objects I can usually do this by simply not providing any setting methods. So my earlier JavaScript class would look like this: [5] class Point { constructor(x, y) { this._data = {x: x, y: y}; } get x() {return this._data.x;} get y() {return this._data.y;} equals (other) { return this.x === other.x && this.y === other.y; } } While immutability is my favorite technique to avoid aliasing bugs, it's also possible to avoid them by ensuring assignments always make a copy. Some languages provide this ability, such as structs in C#. Whether to treat a concept as a reference object or value object depends on your context. In many situations it's worth treating a postal address as a simple structure of text with value equality. But a more sophisticated mapping system might link postal addresses into a sophisticated hierarchic model where references make more sense. As with most modeling problems, different contexts lead to different solutions. [6] It's often a good idea to replace common primitives, such as strings, with appropriate value objects. While I can represent a telephone number as a string, turning into a telephone number object makes variables and parameters more explicit (with type checking when the language supports it), a natural focus for validation, and avoiding inapplicable behaviors (such as doing arithmetic on integer id numbers). Small objects, such as points, monies, or ranges, are good examples of value objects. But larger structures can often be programmed as value objects if they don't have any conceptual identity or don't need share references around a program. This is a more natural fit with functional languages that default to immutability. [7] I find that value objects, particularly small ones, are often overlooked - seen as too trivial to be worth thinking about. But once I've spotted a good set of value objects, I find I can create a rich behavior over them. For taste of this try using a Range class and see how it prevents all sorts of duplicate fiddling with start and end attributes by using richer behaviors. I often run into code bases where domain-specific value objects like this can act as a focus for refactoring, leading to a drastic simplification of a system. Such a simplification often surprises people, until they've seen it a few times - by then it is a good friend. Acknowledgements James Shore, Beth Andres-Beck, and Pete Hodgson shared their experiences of using value objects in JavaScript. Graham Brooks, James Birnie, Jeroen Soeters, Mariano Giuffrida, Matteo Vaccari, Ricardo Cavalcanti, and Steven Lowe provided valuable comments on our internal mailing lists. Further Reading Vaughn Vernon's description is probably the best in-depth discussion of value objects from a DDD perspective. He covers how to decide between values and entities, implementation tips, and the techniques for persisting value objects. The term started gaining traction in the early noughties. Two books that talk about them from that time are are PoEAA and DDD. There was also some interesting discussion on Ward's Wiki. One source of terminological confusion is that around the turn of the century some J2EE literature used "value object" for Data Transfer Object. That usage has mostly disappeared by now, but you might run into it. Notes 1: In Domain-Driven Design the Evans Classification contrasts value objects with entities. I consider entities to be a common form of reference object, but use the term "entity" only within domain models while the reference/value object dichotomy is useful for all code. 2: Strictly this is done in awt.geom.Point2D, which is a superclass of awt.Point 3: Most object comparisons in Java are done with equals - which is itself a bit awkward since I have to remember to use that rather than the equals operator ==. This is annoying, but Java programmers soon get used to it since String behaves the same way. Other OO languages can avoid this - Ruby uses the == operator, but allows it to be overridden. 4: There is robust competition for the worst feature of the pre-Java-8 date and time system - but my vote would be this one. Thankfully we can avoid most of this now with Java 8's java.time package 5: This isn't strictly immutable since a client can manipulate the _data property. But a suitably disciplined team can make it immutable in practice. If I was concerned that a team wouldn't be disciplined enough I might use use freeze. Indeed I could just use freeze on a simple JavaScript object, but I prefer the explicitness of a class with declared accessors. 6: There is more discussion of this in Evans's DDD book. 7: Immutability is valuable for reference objects too - if a sales order doesn't change during a get request, then making it immutable is valuable; and that would make it safe to copy it, if that were useful. But that wouldn't make the sales order be a value object if I'm determining equality based on a unique order number. Share: if you found this article useful, please share it. I appreciate the feedback and encouragement

Vocalizer

Vocalizer

Cool little lib from Atif Azam that allows you to wrap a name in a span and it puts a little 🔊 button to hear the pronunciation. The audio comes from NameShouts. You can't contribute your own pronunciations to NameShouts, best I can tell, but the lib allows you to provide an alternate source. I made a demo based on the screenshot in the README: See the Pen Demo of Vocalizer by Chris Coyier (@chriscoyier) on CodePen. Direct Link to Article — Permalink Vocalizer is a post from CSS-Tricks

The SVG 2 Conundrum

The SVG 2 Conundrum

The SVG we know and love today is "SVG 1.1 2nd edition". SVG 2 is in Editor's Draft status at the W3C, and it's at serious risk of never getting past that, as it's charter may not be renewed before it reaches recommendation status. Tavmjong Bah on part of the reason: While shocking and unexpected, it didn't come out of left field. The active participation in the working group has dropped to just a handful of people, none representing any of the browser vendors. In fact, the last two "face-to-face" meetings had attendance of just three regular participants, one from Canon (which is dropping membership in the W3C as the end of the year) and two invited experts who are working for free. Like Tavmjong, I also spoke with Doug Schepers recently about SVG 2. He ran through most of the major new features for me. This is a good page to see a list of those, along with their status. My hot take after that: There isn't very many killer features for the layman web developer, and it's not overly surprising to me interest all around is waning. Several of the really useful things that are technically SVG 2 are already supported decently (e.g. non-scaling-stroke). I'm usually wrong about stuff. There is a good chance SVG 2 features unlock amazing things that I can't even comprehend right now. There are a few features that are fairly obviously useful. Here's one: z-index. Right now there is no way to control stacking order of SVG elements other than source order. SVG 2 supports z-index and it will just work and that will be useful. No browser is supporting it yet and it's considered "at risk". The Three Way Dance Usually I think of new features on the web as a three way dance between: Developers. They use the features. They are the voice of what is wanted. They are the measuring stick of what actually get used. Browsers. They do the implementing of features. They are the gatekeepers. They have their own ideas on what is needed. They are businesses. Specs. They document how features should work. Browsers look to them to see how to implement features, because the incentive is there to implement features interoperability. They are middlemen. They also have their own ideas of what is needed. Any one of them can exert force and push features along, although ultimately everyone has to agree. Developers can be really loud about a need, which may excite browsers into wanting to deliver for them, or spec authors to jump in and define how it would work. Spec authors may have a serious desire to refine and evolve a language and it's APIs and move things along themselves. A browser might feel strongly that their customers want something (or it makes good business sense to provide something) and move forward with an early implementation. There is plenty of crossover as well. Browser vendor people can work as spec people. Developers are sprinkled everywhere. SVG 2 feels mostly like a spec-driven endeavour. There is a decent amount of interest in SVG right now amongst developers, but perhaps not very much chanting about SVG shortcomings. I find developers are mostly just trying to wrap their heads around what is already there. But this newfound enthusiasm is perhaps what has driven long-time SVG spec-involved people to move forward on SVG 2. As a spec-driven endeavour, it's on them to excite the other parties into action. That's the part that isn't going well so far. From the developer angle, I see it as that lack of killer features. From the browser angle, here's Bah again: There are only two browser implementations of importance: Blink (Chrome/Opera) and Gecko (Firefox). Of these, only Blink has the resources to fully implement new features quickly although Gecko has implemented more of SVG 2. Chrome commands a huge lead in browser market share (almost 75%). Google has a habit of unilaterally removing features it doesn't like from Blink, basically dictating that those features are removed from specifications. Two other significant browser implementations, WebKit (Safari) and Edge, are more followers than leaders and have relatively little market share (5% and 4% respectively). For example, Microsoft explicitly stated that they would not even look at SVG 2 until the specification was a Candidate Recommendation. Read: Blink does whatever it wants; Gecko is slow; Edge won't touch it; WebKit is gonna wait it out. It gets a little worse. The Three Four Way Dance For SVG 2, there is a major fourth player involved: Software. In my estimation, the vast majority of SVG in use on the web wasn't authored directly by developers, but output by software. Inkscape, Adobe Illustrator, Sketch, Affinity Designer... there is loads of software that exports SVG. Let's take another SVG 2 feature, the b or B command as part of the path syntax. It looks like it it will allow for more efficient path output by allowing you to change the angle of trajectory for subsequent path commands. That's great and all, but why would a company like Adobe touch that? If they implement it, they risk outputting SVG that no browser supports, which isn't useful and would certainly irk customers. They almost certainly need to wait for browser support to be very solid before moving on something like that. Which starts a vicious circle: why would browsers implement something no one is ready to take advantage of? So even if the spec gets to some state of finished, and the browsers bite on it, we're still at the mercy of software also taking advantage of it. From The Gut Without knowing more, I lean toward agreeing with the browser vendors. Bah reports: The general consensus from the browser vendors is that SVG 2 should be finished but that it should be restricted to fixing the problems with SVG 1.1 2nd edition along with a few choice selected new features (like 'paint-order') which have already been implemented by multiple browsers. New features (meshes, hatches, etc.) should be removed. Sounds like the removing of new features is pretty painful, but might be the chest of gold you have to toss off the wagon to make it through the pass. The SVG 2 Conundrum is a post from CSS-Tricks

The Power of the rgba() Color Function in CSS

The Power of the rgba() Color Function in CSS

One of the things that I'm really interested in about CSS is the new color-mod function. It will give us the ability to do color manipulations right in the browser. For example, when hovering over a button, you can change the color by using something like color: color(black darkness(50%));, without the use of any CSS preprocessor like Sass. But as the support of these CSS color functions is zero nowadays, we can temporarily use PostCSS and compile them as regular colors. Or we can experiment and discover the power of CSS rgba() color functions to change colors on the fly! Let's see how we can use it. How it works In a design app, when we place a black and white boxes over a bigger box with a blue background color (As in the example), the result will be a lighter and darker blue, respectively. That's because when decreasing the opacity, the colors will blend together based on if it's white or black. Can you expect what will happen if we changed the blue background to green? You guessed it! As you see, by changing the background color to green, the small boxes looks different now! We have light and dark green. We also can change the opacity value to pick a darker or lighter color. Let's work off this basic premise to dive into some real-world examples. Applying the concept To keep the above example concise, we played with the opacity. In our actual design, we will need to use rgba() alpha value. .header { background: rgba(0, 0, 0, 0.5); /* Black color with 50% alpha/opacity */ } We'll use the background instead of opacity here because if we used the opacity value, all of the child elements will be affected, which is not what we want to achieve. If we use the alpha channel of the background property, we're ensured that we'll only update the element that we'd like to change. Note: in the demos we will use Sass rgba() function to make things faster. For example: .elem { background: rgba(white, 0.5); } will be translated to: .elem { background: rgba(255, 255, 255, 0.5); } Theming a website header The first use case for rgba() is to theme a web app header. In Trello they are using a background color with rgba() for the header child elements (logo, search input, buttons): .search { background: rgba(255, 255, 255, 0.5); /* White with 50% alpha */ } With that in place, we will get the ability to theme the header by only changing its background, and then the child elements will change as well. In our example, we will make something similar of Trello header and play with the background from dev tools. Notice how the child elements background color is different in the 2 headers. If we want to inspect element and change the parent background, we can theme our header very easily. See the Pen Header by Ahmad Shadeed (@shadeed) on CodePen. Article header In this example, using rgba() will be beneficial for: Borders at the top and bottom edges. Background color for the centered wrapper. Background color for the category link. .parent { background: #5aaf4c; /* parent background */ box-shadow: inset 0 8px 0 0 rgba(255, 255, 255, 0.5), inset 0 -8px 0 0 rgba(255, 255, 255, 0.5); /* top and bottom borders */ } .contain { background: rgba(0, 0, 0, 0.1); } .category { background: rgba(255, 255, 255, 0.5); } See the Pen Article Header by Ahmad Shadeed (@shadeed) on CodePen. Buttons When theming buttons, we can use rgba() to make the hover and focus effects for things like borders, shadows. .button { background: #026aa7; box-shadow: inset 0 -4px 0 0 rgba(0, 0, 0, 0.2); } .button:hover { box-shadow: inset 0 -4px 0 0 rgba(0, 0, 0, 0.6), 0 0 8px 0 rgba(0, 0, 0, 0.5); } .button:focus { box-shadow: inset 0 3px 5px 0 rgba(0, 0, 0, 0.2); } See the Pen Buttons by Ahmad Shadeed (@shadeed) on CodePen. Gradients Another useful use case is to add the background as a solid color and then use a pseudo element with a rgba() colors for the gradient color stops. .elem { background: green; } .elem:before { content: ""; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: linear-gradient(to right, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.7)); } This will also give us the ability to animate the gradients by only changing the background color. .elem { /* other styles */ animation: bg 2s ease-out alternate infinite; } @keyframes bg to { background: green; } } See the Pen Gradients by Ahmad Shadeed (@shadeed) on CodePen. Sub Element If we have a navigation list inside a header element, we can add a background color with rgba() to the navigation. This will make the background a bit transparent and so it will blend with the parent background. See the Pen Sub Element by Ahmad Shadeed (@shadeed) on CodePen. And the same could be used for making dynamic hover effects: See the Pen Hover Effect by Ahmad Shadeed (@shadeed) on CodePen. Dark/Light Variations of a color palette We can use this concept to generate different shades of a specific color palette by positioning a pseudo element on each color box with a specific rgba() value. See the Pen Color Palette by Ahmad Shadeed (@shadeed) on CodePen. Image Effects If we want to make an image darker or lighter, we can use a pseudo element with rgba() background. By using a colored background, we can create a color tint effect. Other than that, we can use mix-blend-mode property to blend the background with the image so we can different results. It's important to check support tables before using mix-blend-mode: .elem:before { background: rgba(0, 0, 0, 1); mix-blend-mode: color; } If mix-blend-mode is not supported, the image will be black and the user won't get it. It's better to work on such effects as an enhancement, but don't depend on it. To do so, you can use @support or Modernizr. @supports (mix-blend-mode: color) { /* your enhanced styles go there */ } See the Pen Images by Ahmad Shadeed (@shadeed) on CodePen. Theming with CSS Variables By using CSS Variables (custom properties) for the parent elements, when the variable is changed then all child elements will be affected. For example: :root { --brand-color: #026aa7; } /* Checking for the support of CSS Variables */ @supports (--color: red) { .elem { background: var(--brand-color); } } var colors = ["#026aa7", "#5aaf4c", "#00bcd4", "#af4c4c"]; var colorOptions = document.querySelectorAll(".option"); var colorLabels = document.querySelectorAll(".option + label"); for (var i = 0; i < colorOptions.length; i++) { /* Add an event listener to each radio button */ colorOptions[i].addEventListener('click', changeColor); /* Add a value to each radio button based on colors[] array */ colorOptions[i].value = colors[i]; colorLabels[i].style.background = colors[i]; } function changeColor(e) { /* calling the root element and set the value of a specific property. In our case: --brand-color */ document.documentElement.style.setProperty('--brand-color', e.target.value); } By combining CSS Variables and rgba(), we can make our layouts and colors a bit more dynamic without re-defining a new color for each element. See the Pen Header - CSS Variables by Ahmad Shadeed (@shadeed) on CodePen. Things to take in consideration Fallback Color Although the global support for CSS colors is 97.39%, it's important to provide a fallback for non-supporting browsers. .elem { background: #fff; background: rgba(255, 255, 255, 0.5); /* non supporting browsers will ignore this declaration */ } Color Contrast Check We should ensure that the contrast between elements meets the accessibility guidelines. Sometimes, using rgba() might result in a poor color that is very hard to read. You can use tools like Lea Verou's Contrast Check to help determine if colors meet accessibility standards. The Power of the rgba() Color Function in CSS is a post from CSS-Tricks

The Best Tech Jobs in the World

The Best Tech Jobs in the World

Over 4,400 companies are using Hired to find their next team member and with transparency into each company, you’re empowered to make the right decision about what opportunities you’d like to pursue. Say goodbye to pushy recruiters trying to sell you on roles you don’t actually want. Life’s too short to waste time with companies that are a bad fit, or to find out after months of interviewing that the offer is no good. Try Hired and let companies apply to you. The best part: it’s always free. Direct Link to Article — Permalink The Best Tech Jobs in the World is a post from CSS-Tricks

My Increasing Wariness of Dogmatism

My Increasing Wariness of Dogmatism

A couple of definitions, if you are unclear: 1: Positiveness in assertion of opinion especially when unwarranted or arrogant. 2: The tendency to lay down principles as undeniably true, without consideration of evidence or the opinions of others. 3: ... it is applied to some strong belief that the ones adhering to it are not willing to rationally discuss. Hardly a day goes by I don't see a dogmatic statement about the web. I was collecting them for a while, but I won't share them as there is no sense in shaming anyone. I'm as guilty as anyone. The dogmatic part comes from the way an opinion is phrased. I feel like people do it sometimes just for emphasis. To sound bold and proud, via brevity. Never use more than 2 fonts on a page, they say. Stop using jQuery, we're scolded. Never style with ID's, I've extolled. Web fonts aren't worth it, the tweet reads. Websites should never have more than one column at any width, it's declared. The cascade is evil, or so we're told. Those are softies, relatively speaking. The fun ones start with "Say it with me:" or have non-ironic 👏🏽 emojis 👏🏽 between 👏🏽 each 👏🏽 word. Who cares? You might think. It's just people spouting off opinions. Everybodys got 'em. That's what the world is these days. In the end people sort things out for themselves. I'm not so sure. I see ideas that start as dogmatic claims spread. I've heard people regurgitate a dogmatic statement years after I've felt like the industry had moved on. When you happen to agree with them, they feel good. They feel powerful. They feel like something you want to get behind and spread yourself. They don't have that wishy-washy "it depends" feeling that doesn't provide hard and fast answers. After seeing a string of dogma the other day, I created these for some self-catharsis: I'm sure I'll never do anything with them for real. But now I can imagine myself peeling off one of them and sticking it on my screen whenever needed. It beats starting a Twitter argument, that's for sure. What is to be done? Two steps. First, make peace with the fact that the world (and the web) is a huge place with incredible diversity, in every sense of that word. Everyone's situation is different than yours. You can't know everything. There is endless gray area. Second, it's possible to re-work a dogmatic statement into something more productive. For example: ID's come with an extremely high specificity value and, in my experience, limit opportunities to override styling and lead to awkward specificity and selector battles. Here's an example I came across recently... We've spent more hours chasing CSS bugs this year than we're comfortable with. After tracking them down, they are often rooted in styles bleeding into areas they person who wrote them never meant them to. In this light, we're experimenting with encapsulating our styles with... The web at large is suffering from poor performance. Web sites are getting heavier and slower faster than networks can speed up to handle it. Our own site follows the trend. In an effort to tighten our belt and reverse that trend, we're adhering to a new performance budget. We determined that web fonts weren't nearly as crucial to the site as other things, so we're... It's certainly wordier to avoid dogma when you're trying to make a point. But it's more honest. It's more clear. It's showing empathy for people out there doing things different. It makes it easier for others to empathize with you. My Increasing Wariness of Dogmatism is a post from CSS-Tricks

position: sticky;

position: sticky;

Better position: sticky; support is on the horizon. WebKit dropped in 2013, Firefox in 2014, and now Blink in (probably) 2016. MDN explains it well: Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned. Šime Vidas pointed this out in a recent Open Web Platform Daily Digest, and ported over the demo from MDN, which demonstrates the usefulness nicely: See the Pen Sticky positioning by Šime Vidas (@simevidas) on CodePen. As you can see in that demo, it's a decent candidate for progressive enhancement, as if you don't see the sticky header feature, it's no big deal. position: sticky; is a post from CSS-Tricks

IBM Blockchain 101: Quick-start guide for developers

IBM Blockchain 101: Quick-start guide for developers

This developerWorks quick-start guide is for application developers who are new to blockchain technology and want to quickly set up an IBM Blockchain network based on the open source Hyperledger Fabric, deploy chaincode (business rules), and write client apps for Blockchain use cases.

Cooperative Scheduling with `requestIdleCallback`

Cooperative Scheduling with `requestIdleCallback`

Potch: If you absolutely must perform tasks on the main thread (mutating the DOM or interacting with main-thread-only Web APIs), you can now request the browser provide you with a window of time in which it is safe to do so! ... requestIdleCallback allows the browser to wait until it identifies an idle period. An idle period may be a few milliseconds between painting individual frames. This seems like the kind of thing that becomes a best practice. But how do we identify which things we should use this for and what things we shouldn't? Is it like "anytime we touch the DOM we should wrap it in this?" Perhaps with a twist of "unless you're displaying new content to the user, which takes precedence over animation jank." If you're a framework that abstracts away DOM touching (and other main thread tasks), how do you decide to prioritize or not? Direct Link to Article — Permalink Cooperative Scheduling with `requestIdleCallback` is a post from CSS-Tricks