Tag: development

Finding Front-End Development Scholarships

I’m often asked where to learn web development. The answer varies, of course, and we’ve published a few posts on the topic over the years, the most recent of which was Chris taking a stab at different learning paths in 2020.

The answer doesn’t have to be school. But sometimes it is, and if your goal is to earn a degree in front-end web development from a college or university, there are other questions you probably have. One of those is probably how the heck do I afford tuition? That’s the second most-asked question I get from the students I teach at my little city college. (Well, that and if they can get an extension on an assignment.)

Scholarships! That’s the golden ticket, right? Unlike a loan, a scholarship is money you don’t have to pay back. There are strings attached. You might need to write an essay with your application, demonstrate a certain level of academic success, or even complete the program before the any funds are dispersed.

Where to look for scholarships

Good gosh, there are practically hundreds of sites that turn up with a simple online search. The problem is that most of them are aggregate sites littered with ads and affiliate links, many of which busted years ago.

That makes finding a legit source of scholarships like finding a needle in the proverbial haystack. It’s a little easier if your goal is to sign up for some sort of coding bootcamp because those usually offer needs-based discounts up front. But that doesn’t help afford a college degree.

Besides an online search, your best bet for finding scholarships might be on major corporate websites, like Google and Microsoft, both of which offer annually recurring scholarships for a number of programs related to technology.

Finding front-end scholarships

As great as big companies can be for scholarships, you might find it tough to find a scholarship that’s explicitly for front-end development. That’s because many scholarships are only loosely tied to front-end development. Many of the scholarships I’ve found are more like:

  • Graphic communications
  • Media design
  • Digital media
  • Interactive design
  • Computer science
  • Information technology
  • Video game design

That’s a bummer because you’re essentially applying for a scholarship that’s open to other fields not directly related to front-end development.

And a certain scholarship offered this year might not be offered next year. It all depends on who is doling out the money and how much money they have to give. Often it’s going to be some private foundation, endowment, or small company that offers the most promising scholarships, and it could be a one-time deal. I found that many of the most enticing front-end scholarships ended years ago, but are still popping up all over those pesky aggregate sites that claim to have updated information for the current year.

Some scholarships worth looking at

I went down a few rabbit holes trying to find academic scholarships that specifically say “front-end development” or “web design” in their materials. Again, different scholarships have different strings attached to them and what I found today could be gone tomorrow.

That said, here’s a few (in no particular order) that passed my filters:

Scholarship Who it’s for How much it offers
BOWEN Web Design Scholarship Full or part-time students, with a declared major related to web design or development. $ 1,500
Chee Web Development Scholarship Students embarking on a web-related certificate or undergraduate degree. $ 1,000
The Web Development of Tomorrow Scholarship LGBTQ individuals $ 1,000
Lounge Lizard Web Design Students at an accredited school, or accepted to begin school at an accredited school within 6 months of application. $ 1,000
Digital Excellence Awards Scholarship Students under 25 in an accredited school looking for an education in web design, digital marketing, SEO, or computer science. $ 1,000
Net Solutions Annual Scholarship Students enrolled in a four-year college or university in the U.S., U.K., Canada, or Australia. $ 2,500

There could be more! These were just the ones I found. Link me up to others you know of in the comments and I’ll check ’em out to add to the list.

Front-end adjacent scholarships

If you’re willing to apply for scholarships that are less directly tied to front-end development, there are more to consider:

Online programs that offer scholarships

Not attending a college or university? Coding bootcamps are all the rage, or so I hear, and many of them are offered online with discounts and scholarship opportunities. I can’t personlly vouch for each and every bootcamp out there. If you’re interested in taking one — like maybe Fullstack Academy, Udacity, Coding Dojo, or any of the learning paths at Frontend Masters — then it’s worth a quick check for financial help.

We need better scholarships for budding developers

Seriously! For all the college and university students I know who are enrolled in a front-end development program, there is scant resourcing available to make their education more affordable — at least ones without stipulations for which school you’re attending or that are directly related to the front-end field.

Part of me is tempted to go on some sort of rant, but instead what I’ll say is this is a ripe area for private individuals and companies to step in and make a difference. Sure, there are lots of ways to “give back” and it doesn’t have to be a scholarship.

But I see a big hole here and I imagine it’s relatively easy for any mid-sized company to hand out $ 500-$ 1,000 once a year to promote education. It’s not only good for students and good for the web, but most likely good for the company, too.

Different types of front-end scholarships

Every scholarship I found is either directly tied to front-end development (or web design), or groups front-end development with other loosely-related disciplines. How cool would it be to see scholarships that are specifically for front-end and geared toward front-end disciplines?!

There are so many areas we could support…

  • Accessibility
  • Content management systems
  • Design systems
  • Front-end curriculum design
  • Inclusive design
  • Interoperability
  • Specifications and documentation
  • Technical writing
  • Web performance

…just to name a few.


Finding Front-End Development Scholarships originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

CSS-Tricks

, , ,

Getting Started With WordPress Block Development

Let’s acknowledge that developing for WordPress is weird right now. Whether you’re new to WordPress or have worked with it for eons, the introduction of “Full-Site Editing” (FSE) features, including the Block Editor (WordPress 5.0) and the Site Editor (WordPress 5.9), have upended the traditional way we build WordPress themes and plugins.

Even though it’s been five years since we met the Block Editor for the first time, developing for it is difficult because documentation is either lacking or outdated. That’s more of a statement on how fast FSE features are moving, something Geoff lamented in a recent post.

Case in point: In 2018, an introductory series about getting into Gutenberg development was published right here on CSS-tricks. Times have changed since then, and, while that style of development does still work, it is not recommended anymore (besides, the create-guten-block project it’s based on is also no longer maintained).

In this article, I intend to help you get started with WordPress block development in a way that follows the current methodology. So, yes, things could very well change after this is published. But I’m going to try and focus on it in a way that hopefully captures the essence of block development, because even though the tools might evolve over time, the core ideas are likely to remain the same.

The WordPress Block Editor interface with highlighted areas showing three key features.
The Gutenberg Editor: (1) The block inserter, (2) the content area, and (3) the settings sidebar
Credit: WordPress Block Editor Handbook

What are WordPress blocks, exactly?

Let’s start by airing out some confusion with what we mean by terms like blocks. All of the development that went into these features leading up to WordPress 5.0 was codenamed “Gutenberg” — you know, the inventor of the printing press.

Since then, “Gutenberg” has been used to describe everything related to blocks, including the Block Editor and Site Editor, so it’s gotten convoluted to the extent that some folks depise the name. To top it all off, there’s a Gutenberg plugin where experimental features are tested for possible inclusion. And if you think calling all of this “Full-Site Editing” would solve the issue, there are concerns with that as well.

So, when we refer to “blocks” in this article what we mean are components for creating content in the WordPress Block Editor. Blocks are inserted into a page or post and provide the structure for a particular type of content. WordPress ships with a handful of “core” blocks for common content types, like Paragraph, List, Image, Video, and Audio, to name a few.

Apart from these core blocks, we can create custom blocks too. That is what WordPress block development is about (there’s also filtering core blocks to modify their functionality, but you likely won’t be needing that just yet).

What blocks do

Before we dive into creating blocks, we must first get some sense of how blocks work internally. That will definitely save us a ton of frustration later on.

The way I like to think about a block is rather abstract: to me, a block is an entity, with some properties (called attributes), that represents some content. I know this sounds pretty vague, but stay with me. A block basically manifests itself in two ways: as a graphical interface in the block editor or as a chunk of data in the database.

When you open up the WordPress Block Editor and insert a block, say a Pullquote block, you get a nice interface. You can click into that interface and edit the quoted text. The Settings panel to the right side of the Block Editor UI provides options for adjusting the text and setting the block’s appearance.

The Pullquote block that is included in WordPress Core

When you are done creating your fancy pullquote and hit Publish, the entire post gets stored in the database in the wp_posts table. This isn’t anything new because of Gutenberg. That’s how things have always worked — WordPress stores post content in a designated table in the database. But what’s new is that a representation of the Pullquote block is part of the content that gets stored in post_content field of the wp_posts table.

What does this representation look like? Have a look:

<!-- wp:pullquote {"textAlign":"right"} --> <figure class="wp-block-pullquote has-text-align-right">   <blockquote>     <p>It is not an exaggeration to say that peas can be described as nothing less than perfect spheres of joy.</p>     <cite>The Encyclopedia of world peas</cite>   </blockquote> </figure> <!-- /wp:pullquote -->

Looks like plain HTML, right?! This, in technical lingo, is the “serialized” block. Notice the JSON data in the HTML comment, "textAlign": "right". That’s an attribute — a property associated with the block.

Let’s say that you close the Block Editor, and then some time later, open it again. The content from the relevant post_content field is retrieved by the Block Editor. The editor then parses the retrieved content, and wherever it encounters this:

<!-- wp:pullquote {"textAlign":"right"} -->...<!-- /wp:pullquote -->

…it says out loud to itself:

OK, that seems like a Pullquote block to me. Hmm.. it’s got an attribute too… I do have a JavaScript file that tells me how to construct the graphical interface for a Pullquote block in the editor from its attributes. I should do that now to render this block in all its glory.

As a block developer, your job is to:

  1. Tell WordPress that you want to register a specific type of block, with so-and-so details.
  2. Provide the JavaScript file to the Block Editor that will help it render the block in the editor while also “serializing” it to save it in the database.
  3. Provide any additional resources the block needs for its proper functionality, e.g. styles and fonts.

One thing to note is that all of this conversion from serialized data to graphical interface — and vice versa — takes place only in the Block Editor. On the front end, the content is displayed exactly the way it is stored. Therefore, in a sense, blocks are a fancy way of putting data in the database.

Hopefully, this gives you some clarity as to how a block works.

Diagram outlining the post editor states and how data is saved to a database and parsed for rendering.

Blocks are just plugins

Blocks are just plugins. Well, technically, you can put blocks in themes and you can put multiple blocks in a plugin. But, more often than not, if you want to make a block, you’re going to be making a plugin. So, if you’ve ever created a WordPress plugin, then you’re already part-way there to having a handle on making a WordPress block.

But let’s assume for a moment that you’ve never set up a WordPress plugin, let alone a block. Where do you even start?

Setting up a block

We have covered what blocks are. Let’s start setting things up to make one.

Make sure you have Node installed

This will give you access to npm and npx commands, where npm installs your block’s dependencies and helps compile stuff, while npx runs commands on packages without installing them. If you’re on macOS, you probably already have Node and can can use nvm to update versions. If you’re on Windows, you’ll need to download and install Node.

Create a project folder

Now, you might run into other tutorials that jump straight into the command line and instruct you to install a package called @wordpress/create-block. This package is great because it spits out a fully formed project folder with all the dependencies and tools you need to start developing.

I personally go this route when setting up my own blocks, but humor me for a moment because I want to cut through the opinionated stuff it introduces and focus just on the required bits for the sake of understanding the baseline development environment.

These are the files I’d like to call out specifically:

  • readme.txt: This is sort of like the front face of the plugin directory, typically used to describe the plugin and provide additional details on usage and installation. If you submit your block to the WordPress Plugin Directory, this file helps populate the plugin page. If you plan on creating a GitHub repo for your block plugin, then you might also consider a README.md file with the same information so it displays nicely there.
  • package.json: This defines the Node packages that are required for development. We’ll crack it open when we get to installation. In classic WordPress plugin development, you might be accustomed to working with Composer and a composer.json file instead. This is the equivalent of that.
  • plugin.php: This is the main plugin file and, yes, it’s classic PHP! We’ll put our plugin header and metadata in here and use it to register the plugin.

In addition to these files, there’s also the src directory, which is supposed to contain the source code of our block.

Having these files and the src directory is all you need to get started. Out of that group, notice that we technically only need one file (plugin.php) to make the plugin. The rest either provide information or are used to manage the development environment.

The aforementioned @wordpress/create-block package scaffolds these files (and more) for us. You can think of it as an automation tool instead of a necessity. Regardless, it does make the job easier, so you can take the liberty of scaffolding a block with it by running:

npx @wordpress/create-block

Install block dependencies

Assuming you have the three files mentioned in the previous section ready, it’s time to install the dependencies. First, we need to specify the dependencies we will need. We do that by editing the package.json. While using the @wordpress/create-block utility, the following is generated for us (comments added; JSON does not support comments, so remove the comments if you’re copying the code):

{   // Defines the name of the project   "name": "block-example",   // Sets the project version number using semantic versioning   "version": "0.1.0",   // A brief description of the project   "description": "Example block scaffolded with Create Block tool.",   // You could replace this with yourself   "author": "The WordPress Contributors",   // Standard licensing information   "license": "GPL-2.0-or-later",   // Defines the main JavaScript file   "main": "build/index.js",   // Everything we need for building and compiling the plugin during development   "scripts": {     "build": "wp-scripts build",     "format": "wp-scripts format",     "lint:css": "wp-scripts lint-style",     "lint:js": "wp-scripts lint-js",     "packages-update": "wp-scripts packages-update",     "plugin-zip": "wp-scripts plugin-zip",     "start": "wp-scripts start"   },   // Defines which version of the scripts packages are used (24.1.0 at time of writing)   // https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/   "devDependencies": {     "@wordpress/scripts": "^24.1.0"   } }
View without comments
{   "name": "block-example",   "version": "0.1.0",   "description": "Example block scaffolded with Create Block tool.",   "author": "The WordPress Contributors",   "license": "GPL-2.0-or-later",   "main": "build/index.js",   "scripts": {     "build": "wp-scripts build",     "format": "wp-scripts format",     "lint:css": "wp-scripts lint-style",     "lint:js": "wp-scripts lint-js",     "packages-update": "wp-scripts packages-update",     "plugin-zip": "wp-scripts plugin-zip",     "start": "wp-scripts start"   },   "devDependencies": {     "@wordpress/scripts": "^24.1.0"   } }

The @wordpress/scripts package is the main dependency here. As you can see, it’s a devDependency meaning that it aids in development. How so? It exposes the wp-scripts binary that we can use to compile our code, from the src directory to the build directory, among other things.

There are a number of other packages that WordPress maintains for various purposes. For example, the @wordpress/components package provides several pre-fab UI components for the WordPress Block Editor that can be used for creating consistent user experiences for your block that aligns with WordPress design standards.

You don’t actually need to install these packages, even if you want to use them. This is because these @wordpress dependencies aren’t bundled with your block code. Instead, any import statements referencing code from utility packages — like @wordpress/components — are used to construct an “assets” file, during compilation. Moreover, these import statements are converted to statements mapping the imports to properties of a global object. For example, import { __ } from "@wordpress/i18n" is converted to a minified version of const __ = window.wp.i18n.__. (window.wp.i18n being an object that is guaranteed to be available in the global scope, once the corresponding i18n package file is enqueued).

During block registration in the plugin file, the “assets” file is implicitly used to tell WordPress the package dependencies for the block. These dependencies are automatically enqueued. All of this is taken care of behind the scenes, granted you are using the scripts package. That being said, you can still choose to locally install dependencies for code completion and parameter info in your package.json file:

// etc. "devDependencies": {   "@wordpress/scripts": "^24.1.0" }, "dependencies": {   "@wordpress/components": "^19.17.0" }

Now that package.json is set up, we should be able to install all those dependencies by navigating to the project folder in the command line and running npm install.

Terminal output after running the install command. 1,296 packages were installed.

Add the plugin header

If you’re coming from classic WordPress plugin development, then you probably know that all plugins have a block of information in the main plugin file that helps WordPress recognize the plugin and display information about it on the Plugins screen of the WordPress admin.

Here’s what @wordpress/create-block generated for me in for a plugin creatively called “Hello World”:

<?php /**  * Plugin Name:       Block Example  * Description:       Example block scaffolded with Create Block tool.  * Requires at least: 5.9  * Requires PHP:      7.0  * Version:           0.1.0  * Author:            The WordPress Contributors  * License:           GPL-2.0-or-later  * License URI:       https://www.gnu.org/licenses/gpl-2.0.html  * Text Domain:       css-tricks  *  * @package           create-block  */

That’s in the main plugin file, which you can call whatever you’d like. You might call it something generic like index.php or plugin.php. The create-block package automatically calls it whatever you provide as the project name when installing it. Since I called this example “Block Example”, the package gave us a block-example.php file with all this stuff.

You’re going to want to change some of the details, like making yourself the author and whatnot. And not all of that is necessary. If I was rolling this from “scratch”, then it might look something closer to this:

<?php /**  * Plugin Name:       Block Example  * Plugin URI:        https://css-tricks.com  * Description:       An example plugin for learning WordPress block development.  * Version:           1.0.0  * Author:            Arjun Singh  * License:           GPL-2.0-or-later  * License URI:       https://www.gnu.org/licenses/gpl-2.0.html  * Text Domain:       css-tricks  */

I won’t get into the exact purpose of each line since that’s already a well-established pattern in the WordPress Plugin Handbook.

The file structure

We’ve already looked at the required files for our block. But if you’re using @wordpress/create-block, you will see a bunch of other files in the project folder.

Here’s what’s in there at the moment:

block-example/ ├── build ├── node_modules ├── src/ │   ├── block.json │   ├── edit.js │   ├── editor.scss │   ├── index.js │   ├── save.js │   └── style.scss ├── .editorconfig ├── .gitignore ├── block-example.php ├── package-lock.json ├── package.json └── readme.txt

Phew, that’s a lot! Let’s call out the new stuff:

  • build/: This folder received the compiled assets when processing the files for production use.
  • node_modules: This holds all the development dependencies we installed when running npm install.
  • src/: This folder holds the plugin’s source code that gets compiled and sent to the build directory. We’ll look at each of the files in here in just a bit.
  • .editorconfig: This contains configurations to adapt your code editor for code consistency.
  • .gitignore: This is a standard repo file that identifies local files that should be excluded from version control tracking. Your node_modules should definitely be included in here.
  • package-lock.json: This is an auto-generated file containing for tracking updates to the required packages we installed with npm install.

Block metadata

I want to dig into the src directory with you but will focus first on just one file in it: block.json. If you’ve used create-block , it’s already there for you; if not, go ahead and create it. WordPress is leaning in hard to make this the standard, canonical way to register a block by providing metadata that provides WordPress context to both recognize the block and render it in the Block Editor.

Here’s what @wordpress/create-block generated for me:

{   "$ schema": "https://schemas.wp.org/trunk/block.json",   "apiVersion": 2,   "name": "create-block/block example",   "version": "0.1.0",   "title": "Block Example",   "category": "widgets",   "icon": "smiley",   "description": "Example block scaffolded with Create Block tool.",   "supports": {     "html": false   },   "textdomain": "css-tricks",   "editorScript": "file:./index.js",   "editorStyle": "file:./index.css",   "style": "file:./style-index.css" }

There’s actually a bunch of different information we can include here, but all that’s actually required is name and title. A super minimal version might look like this:

{   "$ schema": "https://schemas.wp.org/trunk/block.json",   "apiVersion": 2,   "name": "css-tricks/block-example",   "version": "1.0.0",   "title": "Block Example",   "category": "text",   "icon": "format-quote",   "editorScript": "file:./index.js", }
  • $ schema defines the schema formatting used to validate the content in the file. It sounds like a required thing, but it’s totally optional as it allows supporting code editors to validate the syntax and provide other additional affordances, like tooltip hints and auto-completion.
  • apiVersion refers to which version of the Block API the plugin uses. Today, Version 2 is the latest.
  • name is a required unique string that helps identify the plugin. Notice that I’ve prefixed this with css-tricks/ which I’m using as a namespace to help avoid conflicts with other plugins that might have the same name. You might choose to use something like your initials instead (e.g. as/block-example).
  • version is something WordPress suggests using as a cache-busting mechanism when new versions are released.
  • title is the other required field, and it sets the name that’s used wherever the plugin is displayed.
  • category groups the block with other blocks and displays them together in the Block Editor. Current existing categories include text, media, design, widgets, theme, and embed, and you can even create custom categories.
  • icon lets you choose something from the Dashicons library to visually represent your block in the Block Editor. I’m using the format-quote icon](https://developer.wordpress.org/resource/dashicons/#format-quote) since we’re making our own pullquote sort of thing in this example. It’s nice we can leverage existing icons rather than having to create our own, though that’s certainly possible.
  • editorScript is where the main JavaScript file, index.js, lives.

Register the block

One last thing before we hit actual code, and that’s to register the plugin. We just set up all that metadata and we need a way for WordPress to consume it. That way, WordPress knows where to find all the plugin assets so they can be enqueued for use in the Block Editor.

Registering the block is a two-fold process. We need to register it both in PHP and in JavaScript. For the PHP side, open up the main plugin file (block-example.php in this case) and add the following right after the plugin header:

function create_block_block_example_block_init() {   register_block_type( __DIR__ . '/build' ); } add_action( 'init', 'create_block_block_example_block_init' );

This is what the create-block utility generated for me, so that’s why the function is named the way it is. We can use a different name. The key, again, is avoiding conflicts with other plugins, so it’s a good idea to use your namespace here to make it as unique as possible:

function css_tricks_block_example_block_init() {   register_block_type( __DIR__ . '/build' ); } add_action( 'init', 'css_tricks_block_example_block_init' );

Why are we pointing to the build directory if the block.json with all the block metadata is in src? That’s because our code still needs to be compiled. The scripts package processes the code from files in the src directory and places the compiled files used in production in the build directory, while also copying the block.json file in the process.

Alright, let’s move over to the JavaScript side of registering the block. Open up src/index.js and make sure it looks like this:

import { registerBlockType } from "@wordpress/blocks";  import metadata from "./block.json"; import Edit from "./edit.js"; import Save from "./save.js";  const { name } = metadata;  registerBlockType(name, {   edit: Edit,   save: Save, });

We’re getting into React and JSX land! This tells WordPress to:

  • Import the registerBlockType module from the @wordpress/blocks package.
  • Import metadata from block.json.
  • Import the Edit and Save components from their corresponding files. We’ll be putting code into those files later.
  • Register the the block, and use the Edit and Save components for rendering the block and saving its content to the database.

What’s up with the edit and save functions? One of the nuances of WordPress block development is differentiating the “back end” from the “front end” and these functions are used to render the block’s content in those contexts, where edit handles back-end rendering and save writes the content from the Block Editor to the database for rendering the content on the front end of the site.

A quick test

We can do some quick work to see our block working in the Block Editor and rendered on the front end. Let’s open index.js again and use the edit and save functions to return some basic content that illustrates how they work:

import { registerBlockType } from "@wordpress/blocks"; import metadata from "./block.json";  const { name } = metadata;  registerBlockType(name, {   edit: () => {     return (       "Hello from the Block Editor"     );   },   save: () => {     return (       "Hello from the front end"     );   } });

This is basically a stripped-down version of the same code we had before, only we’re pointing directly to the metadata in block.json to fetch the block name, and left out the Edit and Save components since we’re running the functions directly from here.

We can compile this by running npm run build in the command line. After that, we have access to a block called “Block Example” in the Block Editor:

If we drop the block into the content area, we get the message we return from the edit function:

The WordPress Block Editor with the block inserter panel open and the pullquote block inserted into the content area. It reads hello from the back end.

If we save and publish the post, we should get the message we return from the save function when viewing it on the front end:

The pullquote block rendered on the front end of the website. It says hello from the front end.

Creating a block

Looks like everything is hooked up! We can revert back to what we had in index.js before the test now that we’ve confirmed things are working:

import { registerBlockType } from "@wordpress/blocks";  import metadata from "./block.json"; import Edit from "./edit.js"; import Save from "./save.js";  const { name } = metadata;  registerBlockType(name, {   edit: Edit,   save: Save, });

Notice that the edit and save functions are tied to two existing files in the src directory that @wordpress/create-block generated for us and includes all the additional imports we need in each file. More importantly, though, those files establish the Edit and Save components that contain the block’s markup.

Back end markup (src/edit.js)

import { useBlockProps } from "@wordpress/block-editor"; import { __ } from "@wordpress/i18n";  export default function Edit() {   return (     <p {...useBlockProps()}>       {__("Hello from the Block Editor", "block-example")}     </p>   ); }

See what we did there? We’re importing props from the @wordpress/block-editor package which allows us to generate classes we can use later for styling. We’re also importing the __ internationalization function, for dealing with translations.

The pullquote block on the back end, selected and with devtools open beside it displaying the markup.

Front-end markup (src/save.js)

This creates a Save component and we’re going to use pretty much the same thing as src/edit.js with slightly different text:

import { useBlockProps } from "@wordpress/block-editor"; import { __ } from "@wordpress/i18n";  export default function Save() {   return (     <p {...useBlockProps.save()}>       {__("Hello from the front end", "block-example")}     </p>   ); }

Again, we get a nice class we can use in our CSS:

The pullquote block on the front end, selected and with devtools open beside it displaying the markup.

Styling blocks

We just covered how to use block props to create classes. You’re reading this article on a site all about CSS, so I feel like I’d be missing something if we didn’t specifically address how to write block styles.

Differentiating front and back-end styles

If you take a look at the block.json in the src directory you’ll find two fields related to styles:

  • editorStyle provides the path to the styles applied to the back end.
  • style is the path for shared styles that are applied to both the front and back end.

Kev Quirk has a detailed article that shows his approach for making the back-end editor look like the front end UI.

Recall that the @wordpress/scripts package copies the block.json file when it processes the code in the /src directory and places compiled assets in the /build directory. It is the build/block.json file that is used to register the block. That means any path that we provide in src/block.json should be written relative to build/block.json.

Using Sass

We could drop a couple of CSS files in the build directory, reference the paths in src/block.json, run the build, and call it a day. But that doesn’t leverage the full might of the @wordpress/scripts compilation process, which is capable of compiling Sass into CSS. Instead, we place our style files in the src directory and import them in JavaScript.

While doing that, we need to be mindful of how @wordpress/scripts processes styles:

  • A file named style.css or style.scss or style.sass, imported into the JavaScript code, is compiled to style-index.css.
  • All other style files are compiled and bundled into index.css.

The @wordpress/scripts package uses webpack for bundling and @wordpress/scripts uses the PostCSS plugin for working for processing styles. PostCSS can be extended with additional plugins. The scripts package uses the ones for Sass, SCSS, and Autoprefixer, all of which are available for use without installing additional packages.

In fact, when you spin up your initial block with @wordpress/create-block, you get a nice head start with SCSS files you can use to hit the ground running:

  • editor.scss contains all the styles that are applied to the back-end editor.
  • style.scss contains all the styles shared by both the front and back end.

Let’s now see this approach in action by writing a little Sass that we’ll compile into the CSS for our block. Even though the examples aren’t going to be very Sass-y, I’m still writing them to the SCSS files to demonstrate the compilation process.

Front and back-end styles

OK, let’s start with styles that are applied to both the front and back end. First, we need to create src/style.scss (it’s already there if you’re using @wordpress/create-block) and make sure we import it, which we can do in index.js:

import "./style.scss";

Open up src/style.scss and drop a few basic styles in there using the class that was generated for us from the block props:

.wp-block-css-tricks-block-example {   background-color: rebeccapurple;   border-radius: 4px;   color: white;   font-size: 24px; }

That’s it for now! When we run the build, this gets compiled into build/style.css and is referenced by both the Block Editor and the front end.

Back-end styles

You might need to write styles that are specific to the Block Editor. For that, create src/editor.scss (again, @wordpress/create-block does this for you) and drop some styles in there:

.wp-block-css-tricks-block-example {   background-color: tomato;   color: black; }

Then import it in edit.js, which is the file that contains our Edit component (we can import it anywhere we want, but since these styles are for the editor, it’s more logical to import the component here):

import "./editor.scss";

Now when we run npm run build, the styles are applied to the block in both contexts:

The pullquote block in the WordPress Block Editor with an applied tomoato-colored background. behind black text.
The pullquote block ion the front end with an applied rebecca purple-colored background behind black text.

Referencing styles in block.json

We imported the styling files in the edit.js and index.js, but recall that the compilation step generates two CSS files for us in the build directory: index.css and style-index.css respectively. We need to reference these generated files in the block metadata.

Let’s add a couple of statements to the block.json metadata:

{   "$ schema": "https://schemas.wp.org/trunk/block.json",   "apiVersion": 2,   "name": "css-tricks/block-example",   "version": "1.0.0",   "title": "Block Example",   "category": "text",   "icon": "format-quote",   "editorScript": "file:./index.js",   "editorStyle": "file:./index.css",   "style": "file:./style-index.css" }

Run npm run build once again, install and activate the plugin on your WordPress site, and you’re ready to use it!

You can use npm run start to run your build in watch mode, automatically compiling your code every time you make a change in your code and save.

We’re scratching the surface

Actual blocks make use of the Block Editor’s Settings sidebar and other features WordPress provides to create rich user experiences. Moreover, the fact that there’s essentially two versions of our block — edit and save — you also need to give thought to how you organize your code to avoid code duplication.

But hopefully this helps de-mystify the general process for creating WordPress blocks. This is truly a new era in WordPress development. It’s tough to learn new ways of doing things, but I’m looking forward to seeing how it evolves. Tools like @wordpress/create-block help, but even then it’s nice to know exactly what it’s doing and why.

Are the things we covered here going to change? Most likely! But at least you have a baseline to work from as we keep watching WordPress blocks mature, including best practices for making them.

References

Again, my goal here is to map out an efficient path for getting into block development in this season where things are evolving quickly and WordPress documentation is having a little hard time catching up. Here are some resources I used to pull this together:


Getting Started With WordPress Block Development originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

CSS-Tricks

, , , ,
[Top]

Great (and Free!) Web Development Books You Can Get Online

Right after “Where is the best place to learn?” perhaps the most commonly asked question I hear from folks getting into code is “What web development books should I get to learn?” Well, consider this an answer to that question as I’ve curated a list of books that are not only great for getting into front-end development but also freely available.

Books on CSS

This is the bulk of where we’re going to hang out because, well, this is a site mostly about CSS!

The Magic of CSS by Adam Schwartz

  • Perfect for: Next steps in your CSS journey
  • Learning level: Intermediate
  • Requires: Some basic understanding of CSS

Adam Schwartz covers six CSS concepts in this book, including the box model, layout, tables, color, typography, and transitions. These are things even stump some seasoned CSSers, some of these concepts might be confusing. Adam has gone to a great length to demystify each.

In addition to the book being a great primer on complex CSS concepts, I love how each of the CSS properties mentioned throughout the book is clickable so you can always click on them to see how each is applied. There are many illustrative examples and recommendations for further reading, should you desire to learn more about each chapter.

I found the chapter on colors very interesting not only because it gets into the best practices for using color accessibly, but also because there’s super practical applications, like when Adam gets into using CSS to support an organization’s branding.

Resilient Web Design by Jeremy Keith

  • Perfect for: Developing strategies for writing code
  • Learning level: Intermediate
  • Requires: Some basic understanding of CSS

Straight from the introduction:

You won’t find any code in here to help you build better websites. But you will find ideas and approaches. Ideas are more resilient than code. I’ve tried to combine the most resilient ideas from the history of web design into an approach for building the websites of the future.

What Jeremy does so well is describing soft skills, like planning, outlining, and approaches for writing code. So, rather than dropping in code snippets throughout the book, what you’ll find are details about code strategies, such as progressive enhancement, deciding on what tooling to use, and the challenges of writing future-friendly code.

And for those of you who have not had the pleasure of listening to Jeremy narrate content (like he does in the Web History series), there’s an audio file available to download.

Beginning CSS Web Development: From Novice to Professional by Simon Collison

  • Perfect for: The fundamentals of CSS
  • Learning level: Absolute beginners
  • Requires: Nothing but time and motivation

It may be written in 2006, but Simon’s coverage of web standards and accessibility is timeless and relevant today. He provides an understanding of interoperability as well as approaches for building web applications, including the early planning phases that often go overlooked.

The book has two broad parts which are further divided into 16 chapters. Part 1 covers CSS topics, like working with text, links, lists, backgrounds, images, tables, and forms. It really doesn’t skimp on the details either.

Part 2 is all about layout, shedding light on usability and layout manipulation, plus a handy case study. The chapters are arranged in such a way that one chapter naturally flows into the next. Each chapter also contains a concluding section that highlights all the important concepts covered in the chapter.

Indeed, the book provides novice developers a solid background in CSS and helps them gradually with more advanced concepts. It will make your CSS journey easier.

Books on HTML & CSS

CSS and HTML are often taught together, which can be especially helpful when you’re writing your first lines of code and want to know how the two languages interact with one another.

Learn to Code HTML & CSS by Shay Howe

  • Perfect for: Starting your front-end journey
  • Learning level: Beginners
  • Requires: No prior experience at all

Shay refers to this book as a simple and comprehensive guide dedicated to helping beginners learn HTML and CSS. He does this by focusing on common elements of front-end design and development. Some of the lessons covered are Box Model, Positioning, Typography, Background and Gradients, Lists, Media, Forms, and Tables. In the first chapter *Building Your First Web Page, Shay analyzed the contents of a typical website including elements, attributes and setting up the HTML document structure, code validation, selectors and CSS resets. I find the book very instructive especially as it went beyond the surface to address many key concepts with code samples, which you can follow along.

One profound thing about this great book is that, Shay built a complete project from scratch throughout the 12 lessons and at the end of each lesson, he provided a summary and links to the current state of that website (so you can compare with yours if you follow along) and the source code at every stage of the lessons.

If you’re a learner who learns by doing, you will find this material very useful and by the time you’re done, you will have developed a multi page functional website.

An advanced sequel of the course is also available free via the same link.

HTML & CSS: Learn the Fundamentals in 7 Days by Michael Knapp

  • Perfect for: Starting your front-end journey
  • Learning level: Beginners
  • Requires: No prior experience at all

Can you possibly learn everything there is to know about the HTML and CSS in seven days? Probably not, but that’s why this 2017 book by Michael Knapp is focused straight on the fundamentals. Michael delves into a brief history lesson before launching into HTML and CSS structure, logic, and presentation. You’re going to get all up to speed to the point where you should feel pretty confident about putting a basic webpage together, plus a few extras along the way as the book touches on SEO and analytics.

The book is comprised of simple programs that you can run on your computer if you wish to follow along.

The ebook version is available for free on Apple Books, but there is a Kindle version as well if you already have a subscription there.

The Greatest CSS Tricks Vol. 1 by Chris Coyier

  • Perfect for: Marveling at what CSS can do
  • Learning level: Intermediate
  • Requires: Some CSS experience

Did you know that CSS-Tricks has a book on CSS too? It would be silly to leave that off this list because what you get is a collection of classic CSS trickery that’s explained by none other than Chris Coyier. In fact, Chris handpicked all of the examples covered in the book from his many, many (many!) years running this here site from the plentitude of tricks that have crossed his desk.

Each trick solves a particular pain point. For instance, the first “Pin Scrolling to Bottom” trickdemonstrates how the overflow-anchor CSS property can be used to create the same chat-like interface of a tool like Slack, where the screen is anchored at the bottom in a way that feels as though the page is scrolling for you as new items are added.

Books on process

Code is just as much about how we write code and collaborate on projects with others as it is about the actual code we write. The following books are great starting points for everything from planning and project management to communicating and collaborating with others.

Collaborate: Bring People Together Around Digital Projects by Ellen De Vries

  • Perfect for: Being a better collaborator
  • Learning level: N/A
  • Requires: An open mind to working well with others!

Ellen addresses something in this book that we all have to deal with: collaborating with others. And it’s no small deal — the book is divided into four parts that go super deep into things we can go to work well with others:

  • Know how to prepare the ground and create the right conditions for collaboration.
  • Nurture the group culture in the early stages of collaboration.
  • Maintain a healthy collaborative process.
  • Reap the rewards of a collaboration.

As a content strategist, Ellen has the right kind of experience to help anyone be part of a collaborative project, or get the most from a collaboration.

The Modern Web Design Process by webflow

  • Perfect for: Senior designers, project managers
  • Learning level: N/A
  • Requires: Some basic understanding of CSS

This free ebook features a seven-step design process that’s meant to help define the workflow for today’s brand of web design.

That includes:

  • Setting goals
  • Defining scope
  • Sitemaps and wireframes
  • Working with content
  • Handling visual elements
  • Testing
  • Shipping

Anyone starting a new design project or in the middle of a design project will find the invaluable insights throughout the book. And what’s most remarkable is how this is written in a way that almost feels as though you are being hand-held through an entire project from concept to completion.

Designing for the Web by Mark Boulton

  • Perfect for: Learning to work with clients
  • Learning level: Beginners
  • Requires: A genuine interest in design

It seems many organizations tackle design differently. But author Mark Boulton documents a thorough design workflow in Designing for the Web that de-mystifies many challenges and covers everything you need to know.

What’s unique about this book is that it’s really about work. Sure, there’s a bunch of hugely valuable information on design best practices for things like typography, color, and layout, but what you’re really going to take away from this book is how these fit into a design workflow. It teaches you how to research, the technologies we have to implement ideas, and ultimately, how to work with others as well as clients — perfect fodder for folks including design leads, project managers, freelancers, or anyone who’s involved in the project delivery process.

Learn Version Control with Git by Tower

  • Perfect for: Mastering Git
  • Learning level: All levels welcome
  • Requires: No prior knowledge at all

In this book, the team behind the popular Tower client for Git introduce learners to the crux of version control system using Git. Developers who work in teams will particularly find this very useful, as it helps in effectively collaborating with team members building different features of a project even when you’re thousands of miles apart. That said, it’s still really great for anyone who might be shy of the command line and wants to build confidence there.

And since the book is by the maker of an application that interacts with Git, you’re going to get a nice dose of using Tower as a GUI in addition to working directly on the command line.

So, whether it’s committing, branching, merging, pull requests, forking work, or handling merge conflicts, you’re going to get a whole lot from this book.

Books on JavaScript

Learning JavaScript always seems to be en vogue. In fact, Jason Rodriguez wrote about the JavaScript learning landscape in 2018 and provided a nice list of free books. Not too much has cropped up since then, but here are my thoughts on the following books.

Eloquent JavaScript by Marijn Haverbeke

  • Perfect for: Getting better at writing JavaScript
  • Learning level: Intermediate to seasoned developers
  • Requires: Prior JavaScript experience

Eloquent JavaScript really lives up to its name. Personally, I consider this one of the best-written JavaScript books I have ever come across. Marjin’s writing style is engaging, especially with how he introduces programming concepts and carries the reader along. In his words, the book is simply about instructing computers and making them do what you want them to do.

The book is a deep dive into JavaScript spread across three parts and 21 chapters. You’re going to read a bunch about basic programming concepts, such as values, types, operators and functions, to advanced concepts like regular expressions, modules, the DOM, and asynchronous programming. He starts every chapter with a somewhat philosophical quote to prepare the reader for what lies ahead and then dives straight into the topic.

Plus, there’s three projects to help you practice your newfound skills.

Understanding JavaScript Promises by Nicholas C. Zakas

  • Perfect for: Those who want to learn all about asynchronous programming with promises in JavaScript.
  • Learning level: Intermediate
  • Requires: Basic JavaScript chops

JavaScript promises were introduced in 2015 as part of the ES6 specification to handle asynchronous functions in JavaScript. According to MDN:

A promise is an object representing the eventual completion or failure of an asynchronous operation

In this 51-page book, Nicholas explains the concept of Promises over three chapters: Basics, Chaining Promises, and Working with Multiple Promises. Although the link to the book we’re providing is the free community version, the full version (available on Amazon) has two more chapters on Async Functions and Unhandled Rejection Tracking. Nicholas simplified the concept of Promises with several illustrations and examples. You will learn how to use then(), catch(), and finally() and understand how to chain multiple promises together. Nicholas also covers the assignment of rejection and settlement handlers. You may want to give the book a read to solidify your understanding of the topic.

Nicholas is a veteran JavaScript book author who has been writing about JavaScript for over 15 years. He brings his wealth of experience to bear in this book (just as he has in his work here at CSS-Tricks).

Speaking JavaScript by Alex Rauschmayer

  • Perfect for: Leveling up from beginning JavaScript
  • Learning level: Intermediate
  • Requires: Knowledge of object oriented programming

This book is presented in four chapters covering more than 30 topics. Here’s how it breaks down:

  1. The first chapter is a nice refresher on syntax, variable types, functions and exception handling.
  2. The second chapter offers historical perspective into JavaScript as a prelude for the types of features covered throughout the rest of the book.
  3. Chapter 3 is presented as more or less a reference book with short, clean examples.
  4. The final chapter outlines tips, tools and libraries to help write better JavaScript and follow best practices.

Secrets of the JavaScript Ninja by John Resig and Bear Bibeault

  • Perfect for: Creating a cross-browser JavaScript library from the ground up
  • Learning level: Intermediate
  • Requires: Some prior programming experience

There’s actually a newer edition of this book, but the 2012 edition is the one that’s free. Either way, it’s a good opportunity to learn from John Resig; you know, the guy who created jQuery.

The techniques covered here include closures, functions, the DOM, object orientation with prototypes, and cross-browser strategies. One nice perk is that each chapter is followed by a brief recap that’s perfect for a reference once you’ve finished the book.

Learning JavaScript Design Patterns by Addy Osmani

  • Perfect for: Learning to write more efficient JavaScript
  • Learning level: Intermediate
  • Requires: A decent level of JavaScript experience

The concept of design pattern refers to a reusable solution to a commonly recurring problem in application development. In this book, Addy Osmani covers the implementation of common design patterns using ES6 and beyond, as well as React-specific design patterns, which can be super handy when working on complex React apps where maintainability is a primary goal.

Some of the patterns covered include Singleton, Proxy, Provider, Prototype and Observer patterns. In some cases, Addy includes pros and cons of using some of these patterns and how they may affect the performance of your application.

You Don’t Know JS by Kyle Simpson

  • Perfect for: Mastering JavaScript
  • Learning level: Beginner
  • Requires: Little or no prior programming experience

While the title might be a bit provocative, what Kyle is implying here is that he writes this book assuming you have no prior JavaScript experience whatsoever.

Kyle begins starts by going through the rudiments of programming as seen through the lens of JavaScript. He then proceeds, in subsequent chapters, to introduce more advanced concepts like scope and closure, the this keyword, object prototypes, async, and performance.

There’s a lot of excellent details and explanations in here, and Kyle makes it super easy to understand by avoiding super technical jargon. There is also many exercises designed to reinforce your learning. This book will definitely get you up to speed with JavaScript. There’s second edition of the book in the works that you can track in GitHub.

The JavaScript Beginner’s Handbook by Flavio Copes

  • Perfect for: A beginner’s reference
  • Learning level: Just getting started
  • Requires: Email sign-up, maybe some prior experience

Flavio has put together a very useful JavaScript reference for those just starting out. It’s more like a quick reference guide than a textbook, so those of you just starting out might want to consider this as something you keep on your desk rather than something you sit with for long periods of time.

JavaScript for Data Science by Gans, Hodges & Wilson

  • Perfect for: Getting into data visualizations
  • Learning level: Intermediate to advanced
  • Requires: A decent handle on JavaScript

The authors cover core features of modern JavScript, including callbacks, promises, inheritance, objects and classes. They also get into testing using Mocha, React, and data vizualization, all of which are great for anyone looking to level up their code and how its written. The book doesn’t get as deep into many the concepts as some of the other books, but it really shines when it gets into data science.

The book uses Data-Forge; a JavaScript library designed for working with tabular data. There are numerous exercises to help readers keep up to speed with the subject of discussion. The last chapter also includes a capstone project that pulls everything together.

Wrapping up

I sure hope this collection of books help you, whether you’re taking your first steps in front-end web development, have a dozen years under or belt, or you fall somewhere in between. I know how hard it is to get into something new for the first time and the feeling of not knowing where to look. I also know how it feels to hit a plateau and need something to level me up. There should be something for everyone here, regardless of where you are in your learning journey.

And, hey, if you have any other books that are available to snag for free online, please share them in the comments! I bet we can get an even bigger list going.


Great (and Free!) Web Development Books You Can Get Online originally published on CSS-Tricks. You should get the newsletter.

CSS-Tricks

, , , ,
[Top]

6 Useful Bookmarklets to Boost Web Development

A bookmarklet is a JavaScript-based bookmark that adds to a web browser. I’d like to show you some awesome web browser hacks to aid your web development workflow and how to convert those hacks into time-saving bookmarklets.

  1. Activating design mode
  2. Applying a background to everything
  3. Simulating events
  4. Setting cookies
  5. Toggling classes
  6. Color widget bookmark
  7. What other bookmarklets can you think of?

Activating design mode

Design mode (styled as designMode since it’s a JavaScript property) is for who like to experiment with variations of copy on a live website. For example, copywriters who like to observe how content reads within the flow of the website’s design, or, say, designers who want to ensure that text fits comfortably within a certain space at a certain font size.

JavaScript has a mightily simple feature that can render an entire HTML document editable. It works exactly like HTML’s contenteditable="true" name-value attribute (or contentEditable="true" in JavaScript) but for the whole document. If you’d like to see how it works, start by entering the browser’s console using the relevant keyboard shortcut:

  • Chrome: Option + + J / Shift + CTRL + J
  • Firefox: Option + + K / Shift + CTRL + K
  • Safari: Option + + C / Shift + CTRL + C

Next, type document.designMode="on" into the console, hit Return, and then click on any text element. You’ll see that this text element (and all other text elements) are now editable simply by clicking on them. This method of editing text on a live website is much faster than having to open DevTools, then right-clicking and selecting the “Edit Text” option… and much less tiresome.

Showing an edited version of the CSS-Tricks guide landing page using the design mode bookmarklet.
“Guides and Thangs” — my favorite part of CSS-Tricks

While I’m not sure that “design mode” is the most accurate description of the feature, it’s super useful nonetheless and it’s actually been around for a really long time, surprisingly.

And what’s even an even faster way to enable it? A bookmarklet, of course! Create a bookmark using javascript: document.designMode="on";void 0; as the URL.

Showing the bookmarklet installation.

Applying a background to everything

When HTML elements don’t have backgrounds, it can be difficult to visualize their bounds and/or accurately measure the distance between them and other elements. Developers might want to better visualize bounds when dealing with optical imbalance (i.e. when something “looks off” even though it’s not), margin collapse (when certain margins are ignored), various issues with display:/float:/position:, and more.

Applying backgrounds means applying a semi-transparent background to all HTML elements in order to better visualize their bounds and spacings. It’s something many of us commonly do by opening up DevTools then typing a CSS declaration like selector { background: rgb(0 0 0 / 10%); } into the “Styles” box. But again, it’s really tiresome and repetitive — and something we can simplify with a bookmarklet.

Once again, to create a bookmark, we’re going to make a URL. Here’s what we can use for this one:

javascript: document.querySelectorAll("*").forEach(element => element.style.background="rgb(0 0 0 / 10%)");

We’re using a semi-transparent background because the transparency stacks, which ensures that every nested element is distinguishable and the distances between them can be measured.

Showing the CSS-Tricks guides landing page with all backgrounds fill with varying shades of gray.
Apply a background to everything to see what’s happening.

Simulating events

Have you ever had to test a web event that first requires a series of interactions, or certain conditions to be met? It’s super time-consuming to have to test or debug these kinds of functionalities. This event simulation bookmarklet can be used to instantly trigger specific events, making testing a breeze.

Simulating an event means coding a “throwaway” button that triggers a JavaScript event, making it much easier to quickly and repeatedly test the event without having to meet any usual user-facing conditions, like needing to be logged in.

Assuming that you have your JavaScript event listeners set up, create a bookmark for each event that you’d like to trigger/simulate and submit the following URL:

javascript: document.querySelector("SELECTOR").click();

Replace “SELECTOR” with your unique selector, replace “click” with “focus” or “blur” (when necessary), or extend the snippet to make it trigger more complex events, like scroll.

Setting cookies

Cookies are tokens that are stored on a website visitor’s computer by the website that they’re visiting. Cookies contain data that can be read by the website that created them until they’ve exceeded their expiration date or have been deleted. The mere existence of a cookie can determine whether or not a visitor is logged in, whereas the data itself can store user information.

An example of a scenario where you might want to set a cookie using a bookmarklet is when you want to force a logged-in state during website testing. Websites often look very different for users that are logged in, however, logging in and out eventually becomes very tedious, so this bookmarklet can save quite a bit of time.

Manually writing expires= dates for cookies is awkward as heck, but luckily this create-your-own-set-cookie-bookmarklet app can generate a bookmarklet for a specific cookie, if you know its exact name.

Toggling classes

You may want to add or remove a class from an HTML element in order to trigger a fresh state or a change in appearance, otherwise known as toggling classes. Class toggling happens behind the scenes of most live websites, but it can also be used during testing to skip having to meet certain user-facing conditions.

Class toggling can be used to trigger changes in appearance (e.g. alternative themes or states) and even animations, but it can be a little fiddly when doing it with developer tools when it’s only for testing reasons (i.e. the website doesn’t actually function that way for users). Similar to the other bookmarklets, use this one to rapidly toggle classes and save yourself time.

Create the following bookmarklet to target all elements that match your chosen “SELECTOR”, which, in turn, toggles the “CLASS.”

javascript: document.querySelectorAll("SELECTOR").forEach(element => element.classList.toggle("CLASS"));

Color widget bookmark

While not technically a “bookmarklet,” this bookmarkable data URI by Scott Jehl opens up an <input type="color"> in a new tab:

data:text/html;charset=utf-8,%3Chtml%3E%3Ctitle%3EColor Picker%3C%2Ftitle%3E%3Cinput type%3D"color"%3E%3C%2Fhtml%3E

Why is that cool? Well, how many times have you needed to grab a color value off a page, only to find yourself cracking open DevTools, clicking through a bunch of elements, and pouring over CSS properties to find the value? Better to run this little guy, click the element, and get a color right away!

What other bookmarklets can you think of?

Are there any overly repetitive web development workflows that require you to use the web browser’s sometimes-awkward developer tools? If so, it’s super easy to create your own time-saving bookmarklets. Just remember to start the URL with javascript:!

And if you’ve made a bookmarklet to simplify your workflow, I’d love to see it! Share them here in the comments and let’s get a nice collection going.


6 Useful Bookmarklets to Boost Web Development originally published on CSS-Tricks. You should get the newsletter.

CSS-Tricks

, , ,
[Top]

Netlify Identity, a Key Aspect to Jamstack Development

(This is a sponsored post.)

Netlify is amazing at static file hosting, but it’s really so much more than that. You can build any sort of website, even highly dynamic apps, with the Jamstack approach and static file hosting at the core.

Say you want to build a TODO app with users. Those users will need to sign up and log in. Can’t do that with a static site, right? You can, actually. Netlify helps with Netlify Identity, a robust offering they’ve had for years. Enabling it is just a few clicks in the admin UI, and they even provide auth widgets so you have to build precious little to get this working.

Showing a login widget powered by Netlify Identity.

Now you’ve got a website with authentication, great! But how do you keep going with your TODO app? You’ll need some kind of cloud storage for the data on your user’s lists. For that, you’ll have to reach outside of Netlify to find a cloud storage provider you like. Netlify has had a first-class integration with Fauna for years, so that’s a good choice.

You’ll need to communicate with Fauna, of course, and being a static site, JavaScript is how that’s going to work. Fortunately, your client-side JavaScript can communicate with your own server-side JavaScript that Netlify helps with, which is called Netlify Functions. That’s right, Netlify helps you build/deploy Lambda functions. This means you can actually have the Lambda functions do the communicating with Faunda, keeping your API keys safe.

Those are the building blocks. This is a well-worn approach, and really at the heart of Jamstack. Need a head start? Netlify has templates for this kind of thing. Here are some examples with this approach in mind: netlify-fauna-todo-app and netlify-faunadb-example. We even have a tutorial that covers that. And there’s a one-minute video demo:

There you have it, a website that is every bit as dynamic as something you’d build with a traditional server. Only now, you’re building with Netlify meaning you get so many other advantages, like the fact that you’re deploying from commits to a Git repository and getting build previews, and every other amazing feature Netlify offers.


Netlify Identity, a Key Aspect to Jamstack Development originally published on CSS-Tricks. You should get the newsletter and become a supporter.

CSS-Tricks

, , , ,
[Top]

How to Use an iPad for WordPress Theme Development

I recently started university and, before buying a MacBook Air (the M1 chips are amazing by the way), I had to use an iPad Pro for class. However, being a Computer Science student meant I had to find a way to use it for programming. Therefore, I started my quest to find the best way to program using an iPad.

The first options I found were good, but not great, as I couldn’t run any code or program I want, due to lack of command-line or root access. I could’ve used platforms like Coder, Gitpod, GitHub Codespaces or even Replit, but they were not what I was searching for.

But then, I found the perfect program. It is free, open-source, and self-hostable. It’s also the base for Coder, a platform I found while searching. It’s called code-server and it’s basically a hosted VS Code, with full file-system access to your server.

At first, my use case was for Java programming (it’s the language we’re learning in class), but I soon realized that I could also use it for other programming tasks, namely, WordPress theme development!

Requirements

You’ll need two things to get started:

  • A Linux server with root access. I personally use a VPS from OVH. A Raspberry Pi will work, but the steps are more involved and are beyond the scope of this article.
  • An iPad, or any other device that usually can’t be used for programming (e.g. Chromebook).

I’ll assume you’re working on the same server as your WordPress website. Also, as a note, this guide was written using Ubuntu 20.04.2 LTS.

Installation

We’ll first need to SSH into our server. If you’re using an iPad, I suggest Termius, as it works really well for our needs. Once we’re logged in to our server, we’ll install code-server, which requires root/sudo access.

Installing it is really simple; in fact, it’s only a single terminal command. It’s also the same command when upgrading it:

curl -fsSL https://code-server.dev/install.sh | sh

Configuration

Once code-server is installed, there’s a couple of ways we could go about configuring it. We could just run code-server and it would work—but it would also lack HTTPS and only offer basic authentication. I always want HTTPS enabled and, besides, my domain requires it anyway.

To enable HTTPS, there’s, again, a couple of ways of doing it. The first one in code-server’s docs uses Let’s Encrypt with a reverse proxy, such as NGINX or Caddy. While this works great, it requires a lot more manual configuration and I didn’t want to bother with that. However, code-server also provides another option, --link, which works great, despite it being in beta. This flag steps up a TLS certificate, GitHub authentication and a dedicated cdr.co URL! All without any configuration on our side! How cool is that‽ To set it up, run this command (no need for root/sudo access for this, any regular user works):

code-server --link

That creates a URL for us to login to your GitHub account, so that it knows which account to authorize. Once that’s done, we’ll get a dedicated URL and we’re good to go! Each user has their own configuration and GitHub account, so I think it might be technically possible to run multiple instances at the same time for multiple people. However, I have not tested it.

Once the GitHub account has been configured, we’ll press Ctrl+C to stop the process.

Running code-server --link gives us a login URL.

Tapping the URL in Termius enables us to open it in Safari.

GitHub authorizes your account after logging in.

Once the app is authorized, it should drop you right into a familiar interface!

Going back to our SSH session, we can see that the permanent URL is now available! Keep in mind it’ll only work when code-server is running.

Setting up WordPress theme dependencies

There’s a lot of ways to go about developing a WordPress theme, but I really like the way Automattic’s underscores (_s) is done, so we’ll use that as a starting point.

To start using _s, let’s install Composer. Since I am assuming you’re on the same server as your WordPress website, PHP is already installed. While I could list the steps here, Composer’s website already has them laid out better than I possibly could.

Once Composer is installed, we need to install Node.js by running these commands in terminal:

cd ~ curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh sudo bash nodesource_setup.sh sudo apt install nodejs node -v

These commands add the updated Node PPA—since Ubuntu’s included one is really outdated (Node 10!)—then installs Node, and gets its version.

The last command should have returned something like v16.6.1, which means we’re all set!

Setting up the theme

To setup the _stheme, we run npx degit automattic/_s my-cool-theme. This downloads the _scode to a folder called my-cool-theme. If you want the theme directly in your WordPress themes directory, you can either move that folder, make a symlink to it, or give the full path to the folder in the previous command instead. I personally prefer zipping my files by running npm run bundle and then unzipping them manually in my themes folder.

Once all that’s done, let’s run code-server --link, open up our browser and navigate to our URL!

In our VS Code instance, we can open the folder containing our theme and follow the quick start steps for _s, to name our theme correctly. Then, in the integrated terminal, we run composer install and npm install. This installs all the required packages for the theme. I won’t explain the way a WordPress theme works, since a lot of more experienced people have already done that.

And… that’s it! Our server now has everything we need to develop some sick WordPress themes using an iPad or any other device that has a browser and a keyboard. We could probably even use an Xbox, once their new browser releases.

What development looks like

Everything we talked about sounds great in theory, right? What you’re probably wondering, though, is what it’s actually like to develop on an iPad with this configuration. I recorded the following video to show what it’s like for me. It’s a few minutes long, but gives what I think is a good reflection of the sorts of things that come up in WordPress development.

A few notes on this setup

Since code-server is using the open-source VS Code—not Microsoft’s version—some things are missing. It’s also not using Microsoft’s marketplace for extensions, which means that not all extensions are available. We cannot login to our Microsoft or GitHub account to sync our settings, but we can also use the Settings Sync extension, though I personally had trouble using it to sync my extensions. Each Linux user has their own settings and extensions, saved in this folder: ~/.local/share/code-server. It’s a similar folder structure as a regular VS Code install.

There are also ways to run code-server as a service instead of directly in the SSH session, so that it always run, but I prefer to open it when I need it.

Some iPad-specific tips

If you’re planning on using an iPad like me, here are some tips to make your experience more enjoyable!

CSS-Tricks

, , ,
[Top]

I completely ignored the front-end development scene for 6 months. It was fine.

Have you ever fretted that front-end web development moves so fast that if you stepped away for a while, you’d be lost coming back? Rachel Smith has:

The hectic pace of needing to learn one thing after the next didn’t bother me so much because when I was 26 because I was quite happy to spend much of my free time outside of my day job coding. I was really enjoying myself, so the impression that I had to constantly up-skill to maintain my career wasn’t a concern. I did wonder, though, how I would ever take enough time off to have a baby, or have other responsibilities that would prevent me from being able to spend so much of my time mastering languages and learning new libraries and frameworks.

And then, as is inevitable for most of us, she did take a break. And as you read in the title, it was fine:

What I’ve learnt through experience is that the number of languages I’ve learned or the specific frameworks I’ve gained experience with matters very little. What actually matters is my ability to up-skill quickly and effectively. My success so far has nothing to do with the fact I know React instead of Vue, or have experience with AWS and not Azure. What has contributed to my success is the willingness to learn new tools as the need arises.

I might be extra qualified to verify this claim, as I work directly with Rachel. She’s better than “fine” as a team member and technological contributor, both on the front-end and back. She’s extremely good. And you will be too if you heed Rachel’s advice: be a lifelong learner and be willing to learn new tools as the needs arise.

Direct Link to ArticlePermalink


The post I completely ignored the front-end development scene for 6 months. It was fine. appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , , , ,
[Top]

Principles for user-centered front-end development

Colin Oakley:

Accessible — Use semantic HTML, and make sure we meet the WCAG 2.1 AA standard as a minimum and it works with assisted technologies (this sits alongside the DWP Accessibility Manual)

• Agnostic — Build mobile-first and make it work across a range of devices, and user contexts

• Robust — Use progressive enhancement, make sure what we build fails gracefully

• Performant — Optimise our code/assets for the best possible performance across a range of networks and devices

• Secure — Create a secure service which protects users’ privacy. Use strict content security policies and guard against common OWASP attacks.

Direct Link to ArticlePermalink


The post Principles for user-centered front-end development appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , ,
[Top]

Creating Powerful Websites with Serverless-Driven CMS Development

Choosing the right tools to build a website for your organization is essential, but it can be tough to find the right fit. Simple site builders like Wix and Squarespace are easy for marketers to use, but severely limit developers when it comes to customizing site functionality. WordPress is a more robust content management system (CMS), but it requires clunky plugins with infrequent updates and potential security issues

Other site-building tools, such as Gatsby or Hexo, are developer-friendly, but make it very challenging for content creators without technical backgrounds to make even simple updates on their own. These tools often don’t meet the needs of large creative teams running corporate websites.

But there is an option that solves for both audiences. HubSpot’s CMS Hub is a content management system powered by a full CRM Platform that empowers developers to build advanced functionality and marketers to make updates and publish content on their own.

One of the features CMS Hub offers developers is the ability to create serverless functions. These functions make it possible to enhance a website’s backend functionality with integrated plugins that are much easier to develop, deploy, and maintain than third-party WordPress plugins. 

Throughout this article, you’ll get a hands-on look at how HubSpot serverless functions help you build custom websites that clients love. To provide a super-quick preview of what is possible, we’ll fetch news data using GET functions that could be used to populate a dynamic webpage. You’ll need to know some JavaScript to follow along. 

HubSpot Serverless Functions

Serverless architecture enables developers to build and run applications and services without managing the server’s infrastructure. You don’t need to provision, scale, and maintain servers or install and manage databases to host and serve your web applications. When your business grows, it is much easier to scale.

HubSpot’s serverless functions are as powerful as WordPress plugins. They are capable of interacting with HubSpot’s CRM platform as well as integrating with third-party services through APIs. You can use serverless functions to enhance your site, for example:

  • Getting data and storing it in HubDB or the HubSpot CRM
  • Integrating your website with third-party services like Google Forms
  • Creating event registration systems
  • Submitting forms that send data to other services

The functions’ code is stored in the developer file system and is accessed from the Design Manager user interface (UI) or the command-line interface (CLI). You can use the CLI to generate and edit the code locally using your preferred local development tools then upload these changes to HubSpot.

To try the example serverless function in the next section, you need to have access to a CMS Hub Enterprise account or sign up for a free developer testing account. We’ll deploy serverless functions into a site created based on the CMS Boilerplate.

(If you are not familiar with HubSpot development, you may want to check out the quick start guide before following along with the examples below.)

Fetching News Data Using GET Requests

Let’s start by implementing a serverless function that sends a GET request to a third-party REST API to fetch the latest news data using the Axios client. This API searches for online news articles that mention the keyword “HubSpot.”

Note: We’ll be using a third-party API available from NewsAPI.org to retrieve news data, so you first need to register for their API key.

APIs that require authentication or use API keys are not safe for a website’s frontend as they expose your credentials. Serverless functions are a good solution as an intermediary, keeping your credentials secret.

Head over to a CLI and run the following commands:

cd local-cms-dev mkdir myfunctions hs create function 

First, we navigate to our local CMS project, and we call the hs create function command to generate a simple boilerplate function.

You’ll be prompted for some information about your functions, such as:

  • Name of the folder where your function will be created. Enter myfunctions/getnews.
  • Name of the JavaScript file for your function. Enter getnews.
  • Select the HTTP method for the endpoint. Select GET.
  • Path portion of the URL created for the function. Enter getnews.

You should get a message saying that a function for the endpoint “/_hcms/API/getnews” has been created. This means, once uploaded, our function will be available from the /_hcms/API/getnews endpoint. 

Before uploading the function, let’s first implement our desired functionality.

Open the myfunctions\getnews.function\getnews.js file. You’ll find some boilerplate code for a serverless function that sends a GET request to the HubSpot search API. Remove the boilerplate code and leave only the following updated code:

const axios = require('axios'); const API_KEY = '<YOUR_API_KEY_HERE>';  exports.main = async (_, sendResponse) => {     };

Note that you should normally add your API key via the command-line interface hs secrets command, but adding it here is sufficient for the purpose of demonstrating the function.

We require the Axios library to send HTTP requests, and we export a main function that HubSpot executes when a request is made to the associated endpoint. We also define an API_KEY variable that holds the API key from the news API.

Next, inside the body of the main function, add the following code:

const response = await axios.get(`https://newsapi.org/v2/everything?q=HubSpot&sortBy=popularity&apiKey=$  {API_KEY}`); sendResponse({ body: { response: response.data }, statusCode: 200 });

We call Axios to send a GET request to the API endpoint, then we call the sendResponse method to send the fetched data back to the client. We could call this API directly from the frontend code, but we would need to expose our API key, which should be secret. Thanks to the serverless function, fetching data happens on the server side, so we don’t have to expose the secret.

Finally, run the following command to upload your function:

hs upload myfunctions myfunctions

This command uploads files from the myfunctions local folder to a myfunctions folder (that will be created) in your account’s Design Manager.

Finally, run the method by visiting the /_hcms/API/getnews endpoint with your web browser. In our case, we need to visit this link. Here, you should see a list of news articles about HubSpot – albeit without any front-end design. 

While it is beyond the scope of this article, our next step would be to take the data from the NewsAPI and create a template that would allow us to output the news results onto a dynamic webpage. And with this, we’ll have a place where anyone can quickly catch up on all the latest news mentioning HubSpot or any other keyword you decide to include.  

Next Steps

When you need a small brochure-based website and won’t be making many updates, any CMS will do. However, when you are looking to create advanced digital experiences to grow your organization, HubSpot’s CMS Hub offers the functionality and flexibility you need. Plus, you can work with your preferred tools and modern workflows such as CLIs, integrated development environments (IDEs), and GitHub. 

Hopefully, this article has provided an initial glimpse of what is possible with HubSpot’s serverless functions. But don’t stop here, dive in and experiment with adding custom functionality to your own HubSpot-powered website. Your imagination is the limit. Sign up for a free developer test account to get started.

Further reading:


Ahmed Bouchefra is a developer and technical author with a BAC + 5 diploma in software development. Ahmed builds apps and authors technical content about JavaScript, Angular, Ionic, and more.


The post Creating Powerful Websites with Serverless-Driven CMS Development appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , ,
[Top]

The Power of Web Development Outside Tech

In 2020, I learned about the power of web development for organizations and nonprofits outside of tech. I learned that you can leverage your skills to affect change and build long-lasting partnerships.

This year, I joined the Board of Directors of the League of Women Voters San Francisco (LWVSF), which, despite its name, welcomes people of all genders. This century-old organization has over 800 branches that span cities and states across the United States and the world.

Before joining the Board, I helped lead the LWVSF Observer Corps (and still do), whose focus is increasing government transparency and protecting the public’s participation in government with an emphasis on policing practices. Eventually, my volunteer efforts hit a point where I needed to start editing our website myself.

The first thing I noticed was that every individual League has its own website, user interface, and content. Some use MyLo (a platform developed for Leagues by LWV California), some use SquareSpace, and we at LWVSF use GoDaddy’s “Website Builder”. I quickly learned that base-level HTML, CSS, and inline JavaScript skills with a sprinkling of PHP (for WordPress-based sites) will take one quite far in this realm.

In some ways, the bar outside of the tech industry is lower — for these blogs, and what are otherwise static websites, one doesn’t need much to get started. Coming in as a seasoned software developer, I often found myself frustrated by small things: a limit on the number of displayed events in the editor, the inability to customize PayPal integrations, and unpreserved tabbing and syntax highlighting. Big things too, like unintuitive user interface and information architecture. Imagine attempting to make sense of a website builder without a foundation built on years of tech literacy.

The risks are also super high. If we introduce a website bug, it could mean the loss of essential donations and grants, the failure to recruit potential key members, or the inability to share last-minute information about a government meeting where legislative changes affect marginalized populations.

For me, this points to the importance of partnership between those in tech and those outside of it. Our skills are valuable to the essential work of political organizing. Tools for those working for social good and the betterment of society should be the best. We can help!

Take Rideshare Drivers United (RDU). In 2017, a software developer, Ivan Pardo, and a driver who was also a former union organizer put their heads together and created an app to recruit drivers to RDU. Pardo and I met through the Tech Workers Coalition and RDU’s text banking drive, and we discussed the amazing work he put into the app.

This year, Pardo updated the app with phone and text banking capabilities to help spread the “No on Prop 22” message. This led to the texting of over one million voters, with some individual drivers texting over 50,000 people! The platform is simple, straightforward, and impactful, but most importantly, the platform fits the needs of RDU and supports their activism rather than overshadowing it.

What makes Pardo’s app so good, so effective? He says:

I’m there to serve the group in any capacity necessary. But I’m not a driver. Just because you know software doesn’t mean you understand organizing. I spent just as many hours learning about the industry and that allows me to build software [for RDU] more effectively.

And his advice for getting involved?

Attach yourself to an organization that is pro-people and pro-democracy. Then build software to serve that organization.

As demonstrated by Pardo and RDU, there are clear benefits and a massive impact that stems from the cooperation between tech workers and non-tech organizations. Using our technical know-how to amplify the work of others has stood out to me as a light in the dark, especially in a year like 2020.

Even simple websites and apps go on to make a huge difference politically and socially. We, as website builders, have the benefit that even in a global pandemic, we’re able to organize and operate online.

In the last year, as friends, acquaintances, and myself were laid off in the middle of a global pandemic, I learned about and was inspired by the initiative of so many. Despite being unable to organize in person, I saw my friend Amy working on VoteAmerica, Chris churning out Election Map SF, countless individuals promoting the team behind Native Land, and The Algorithmic Justice League cobbling together AI advocacy resources, just to name a few.


The post The Power of Web Development Outside Tech appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , ,
[Top]