10+ Examples of Responsive Websites That Show Us How to Get It Right

Post pobrano z: 10+ Examples of Responsive Websites That Show Us How to Get It Right

Making sure your website will look good on every browser and device needn’t be an insurmountable challenge. These responsive designs show you how it’s done.

When, according to data from StatCounter, more than half of today’s website traffic is viewed on mobile devices, a web designer is left with three options: (1) stick with desktop browsers, (2) go mobile, or (3) maximize traffic by going with both.

Going with Option 3 requires extra effort, but not all that much, and the rewards are great (if roughly twice the amount of traffic appeals to you).

There’s a list of specs and requirements that must be satisfied in designing a responsive website; but given today’s tools and techniques those specs and requirements needn’t be difficult to satisfy.

High-quality WordPress themes like those BeTheme provides do most of the heavy lifting for you to make designing a responsive website just like taking the proverbial walk in the park.

Both desktop and mobile users have easy access to your site, and Google will reward your responsive, mobile-friendly site with better search rankings

Which is why Responsive web design is a must.

It’s simply not true that responsive design takes desktop users out of the picture. Prioritize the mobile experience, and if you do it well everyone will be happy.

Let’s look at some examples of what “doing it well” involves.

How responsive web designs can encourage leaner yet highly engaging desktop experiences

One advantage of designing for desktop users is having more space, and therefore more pixels to work with. Trying to get the most out of “every pixel” is not only impractical but a poor design approach as well.

Consider the popularity of sites featuring minimalist design techniques or exhibit a generous use of white space.

Designers have in fact learned to create leaner and more efficient desktop experiences in their drive to create effective mobile experiences.

Take designer/developer Rob Grabowski’s website as an example.

On a mobile screen it looks like this:

Website visitors have no problem focusing on the welcoming message and the photo behind it.

Desktop visitors encounter virtually the sameexperience:

This is a great example of seamless transitioning between desktop and mobile displays. With the proper design techniques,it’s not hard to accomplish.

Mobile web designs that simplify and enhance the decision-making process

One of the pitfalls of an over-busy website is that it can present an overabundance of choices or options to the user, which in turn can make choosing between similar options more difficult.

Responsive design techniques force web designers to take a modular approach to designing a site, creating levels of website sections which in turn makes it easier to review one option at a time.

BeRepair, one of the 500+ pre-built sites in BeTheme’s library, does an excellent job of demonstrating this design approach.

This responsive layout makes it easy for the viewer to focus on the message without being distracted by an overabundance of information.

Let’s take a look at a completely different websitetype, in this case the BeRestaurant pre-built desktop site:

Great looking, right? The mobile version is every bit as attractive while featuring fewer details that could prove to be distracting.

Note how the menu has been placed on a separate but readily accessible level by incorporating it into the hamburger menu, allowing the visitor to proceed one step at a time.

Responsive designs that excludeexcessive information

Consider paintings you might encounter in an art museum.

You’ll see landscape murals that are rich in beautiful details yet still tend to have a central focus.

That central focus is generally more clearly defined in portraits, even when surrounded by intricate details.

Responsive websites offer the best of both worlds. When you think of landscape, think desktop, where there is an abundance of space to work with. When you think of portrait, think mobile, there’s less space to work with but more than enough to focus on the message.

To get from one to the other, it’s a matter of knowing what details can be trimmed away as excess in such a way as to ensure the mobile experience remains worthwhile.

BeITService is a good example of this. First, the desktop version:

This is a great looking home page. Plenty of detail, and plenty of space as well in this responsive image. Note how easy it is to remove some of the detail to create the mobile version: 

While some of the image has been trimmed away, it’s fair to say that nothing has really been lost in the transition and the message is still front and center.

Culturally Connected, while involving some rearranging to make the transition, takes a very similar approach.

The desktop version:

The desktop version features a rather elaborate background graphic. Much of the graphic can however be looked upon as excess, giving you this on mobile:

Again, nothing has been lost. The secondary text has been placed in a different section where it will not serve as a distraction.

BeTutor is another great example of this technique. The desktop version looks like this:

To get to the mobile version, the designer simply omits the smaller text. The primary message remains intact.

None of the subject matter that reveals the type of service offered has been removed.The graphic is unchanged, and the design as a whole remains uncluttered.

Responsive websites that leverage their space

The previous two examples removed secondary textin the mobile versions. In the following example, by leveraging space web designers can sometimes take advantage of different screen size ratios.

As  the 1987 Masters demonstrates:

The mobile version on the other hand takes advantage of the vertical space to show additional content that will be of value to the viewer.

While mobile designs are sometimes forced to show less content to work effectively, it doesn’t always have to be that way. BeCosmetics is a good example of this.

The desktop view:

The mobile view leverages the added vertical space to provide the viewer with some useful introductory content plus a button that invites the visitor to check out the product line:

While it may sound counterintuitive, having less space doesn’t always limit the amount of comment if you are able to leverage that space.

Responsive websites that heighten readability

Internet users tend to be an impatient lot to begin with, and even when they find a site to their liking, they’re not apt to put up with text that, for whatever reason, is difficult to read.

It’s not only font type that matters. Too many words on a line or cramped lettering can be enough to cause a reader to bail out.

One helpful hint is to use visual elements to even out the text, as has been done in the BeDanceSchool site.

While it’s easy for visitors to focus on the content on the desktop version, thanks to the eye-catching graphics, the same design won’t work on mobile. By taking advantage of both the strengths and weaknesses of mobile screen size, the problem can be handled like this:

Significantly paring back the graphic designelements enables visitors to easily read the content. The text itself is beautifully styled to support readability.

The choice of font size and type also matters of course. See what Base Coat has done to ensure the text is both readable and engaging:

Be mindful of the fact that, while a vertical format can often be used to advantage with respect to text, lengthy text that requires scrolling can prove to be daunting for mobile users.

Mobile sites that highlightvisual content

Turning from how best to deal with lots of text on mobile sites, let us now take a look athow storytelling elements can contribute to a highly positive mobile experience.

Starting with what visitors experience on BeBand on the desktop:

A mobile screen doesn’t provide nearly as many options to play with design balance as on a desktop, but it can nevertheless highlight whatever image you’ve chosen:

It’s not only website static images that work well on mobile. The Scott Resort, for example, invites its first-time mobile visitors to watch a brief video:

Regardless of the device a visitor is using, a responsive video will automatically conform to the width of the screen.

The video as seen on desktop:

The video on mobile looks like this:

A mobile responsive design gives the maximum number of users the experience you want them to enjoy by allowing your content to adapt to the devices they happen to be using.

Mobile responsive sites that do a great job of accumulating leads

It needs to be emphasized at this point that, while responsive websites will typically generate more traffic, mobile conversion rates are not as high as they are on desktop; a situation that is expected to improve over time.

Given than, a responsive site should be designed to capture as many leads as possible to help achieve an acceptable conversion rate.

The BeClub pre-built website illustrates how this can work:

Note how effectively “Newsletter” is highlighted on the home page, and how it immediately precedes an invitation to subscribe.

The result? A ton of subscribers.

Here’s how the same page appears on mobile:

Not only is it very well done, but the mobile version may be even more effective in engaging potential subscribers due to its smaller,more dedicated space.

As is the case here, and with all the previous examples, website owners receive an extra benefit whenever a visitor uses both desktop and mobile devices.

Responsive web designs for the win

What do WordPress users look for in a theme to base their website design on? Most certainly, they look for many if not all of the following qualities:

  • Easy to work with
  • Cost effectiveness
  • Key features
  • Customizability
  • Overall design quality, including performance

Yet another quality must be added, and that is responsiveness. Not every WordPress theme has been designed with mobile users in mind.

That’s not the case with BeTheme. Each of its more than 500 pre-built websites has mobile responsiveness baked right in. With BeTheme, you won’t have to agonize over how you think your pages might show up on mobile screens. You can spend the time you would have otherwise spent stressing yourself out with worry to getting your site online and building your business.

Hilarious Medieval Paintings of Animals Never Seen by the Artists

Post pobrano z: Hilarious Medieval Paintings of Animals Never Seen by the Artists

As you already know, photography wasn’t a thing in the Middle-Ages. This made reporting on wildlife from other continents much less accurate, as it was impossible to bring back a direct depiction of the animals observed.

In this post, you will see some drawings and paintings created by artists based on the oral or written description made by travellers. As one could expect, the results are not very precise and often hilarious.

This “Hippopotamus” by Jacob van Maerlant sometime around 1350
A 12th Century tiger by an unknown artist.
Probably the most agressive snail ever, by Jacob van Maerlant around 1350.
Weird elephants by unknown artist from the late 13th Century.
Another elephant, without ears this time. Fromt he Bestiary of William the Clerk.
The tornado trunk elephant of Jacob van Maerlant. Year unknown.
A whale that looks pretty much like a dragon, from the 13th Century.
Lions and bears, by an unknown artist of the early 13th Century.
A crocodile that can walk on water, by an unknown artist from the late 13th Century.
Another crocodile, by Eward Topsell in 1658.
A weird looking leopard, funny to see this gracious animal being represented with such a “square” head shape. From the Aberdeen Bestiary.

A Primer on the Different Types of Browser Storage

Post pobrano z: A Primer on the Different Types of Browser Storage

In back-end development, storage is a common part of the job. Application data is stored in databases, files in object storage, transient data in caches… there are seemingly endless possibilities for storing any sort of data. But data storage isn’t limited only to the back end. The front end (the browser) is equipped with many options to store data as well. We can boost our application performance, save user preferences, keep the application state across multiple sessions, or even different computers, by utilizing this storage.

In this article, we will go through the different possibilities to store data in the browser. We will cover three use cases for each method to grasp the pros and cons. In the end, you will be able to decide what storage is the best fit for your use case. So let’s start!

The localStorage API

localStorage is one of the most popular storage options in the browser and the go-to for many developers. The data is stored across sessions, never shared with the server, and is available for all pages under the same protocol and domain. Storage is limited to ~5MB.

Surprisingly, the Google Chrome team doesn’t recommend using this option as it blocks the main thread and is not accessible to web workers and service workers. They launched an experiment, KV Storage, as a better version, but it was just a trial that doesn’t seem to have gone anywhere just yet.

The localStorage API is available as window.localStorage and can save only UTF-16 strings. We must make sure to convert data to strings before saving it into localStorage. The main three functions are:

  • setItem('key', 'value')
  • getItem('key')
  • removeItem('key')

They’re all synchronous, which makes it simple to work with, but they block the main thread.

It’s worth mentioning that localStorage has a twin called sessionStorage. The only difference is that data stored in sessionStorage will last only for the current session, but the API is the same.

Let’s see it in action. The first example demonstrates how to use localStorage for storing the user’s preferences. In our case, it’s a boolean property that turns on or off the dark theme of our site.

CodePen Embed Fallback

You can check the checkbox and refresh the page to see that the state is saved across sessions. Take a look at the save and load functions to see how I convert the value to string and how I parse it. It’s important to remember that we can store only strings.

This second example loads Pokémon names from the PokéAPI.

CodePen Embed Fallback

We send a GET request using fetch and list all the names in a ul element. Upon getting the response, we cache it in the localStorage so our next visit can be much faster or even work offline. We have to use JSON.stringify to convert the data to string and JSON.parse to read it from the cache.

In this last example, I demonstrate a use case where the user can browse through different Pokémon pages, and the current page is saved for the next visits.

CodePen Embed Fallback

The issue with localStorage, in this case, is that the state is saved locally. This behavior doesn’t allow us to share the desired page with our friends. Later, we will see how to overcome this issue.

We will use these three examples in the next storage options as well. I forked the Pens and just changed the relevant functions. The overall skeleton is the same for all methods.

The IndexedDB API

IndexedDB is a modern storage solution in the browser. It can store a significant amount of structured data — even files, and blobs. Like every database, IndexedDB indexes the data for running queries efficiently. It’s more complex to use IndexedDB. We have to create a database, tables, and use transactions.

Compared to localStorage , IndexedDB requires a lot more code. In the examples, I use the native API with a Promise wrapper, but I highly recommend using third-party libraries to help you out. My recommendation is localForage because it uses the same localStorage API but implements it in a progressive enhancement manner, meaning if your browser supports IndexedDB, it will use it; and if not, it will fall back to localStorage.

Let’s code, and head over to our user preferences example!

CodePen Embed Fallback

idb is the Promise wrapper that we use instead of working with a low-level events-based API. They’re almost identical, so don’t worry. The first thing to notice is that every access to the database is async, meaning we don’t block the main thread. Compared to localStorage, this is a major advantage.

We need to open a connection to our database so it will be available throughout the app for reading and writing. We give our database a name, my-db, a schema version, 1, and an update function to apply changes between versions. This is very similar to database migrations. Our database schema is simple: only one object store, preferences. An object store is the equivalent of an SQL table. To write or read from the database, we must use transactions. This is the tedious part of using IndexedDB. Have a look at the new save and load functions in the demo.

No doubt that IndexedDB has much more overhead and the learning curve is steeper compared to localStorage. For the key value cases, it might make more sense to use localStorage or a third-party library that will help us be more productive.

CodePen Embed Fallback

Application data, such as in our Pokémon example, is the forte of IndexedDB. You can store hundreds of megabytes and even more in this database. You can store all the Pokémon in IndexedDB and have them available offline and even indexed! This is definitely the one to choose for storing app data.

I skipped the implementation of the third example, as IndexedDB doesn’t introduce any difference in this case compared to localStorage. Even with IndexedDB, the user will still not share the selected page with others or bookmark it for future use. They’re both not the right fit for this use case.

Cookies

Using cookies is a unique storage option. It’s the only storage that is also shared with the server. Cookies are sent as part of every request. It can be when the user browses through pages in our app or when the user sends Ajax requests. This allows us to create a shared state between the client and the server, and also share state between multiple applications in different subdomains. This is not possible by other storage options that are described in this article. One caveat: cookies are sent with every request, which means that we have to keep our cookies small to maintain a decent request size.

The most common use for cookies is authentication, which is out of the scope of this article. Just like the localStorage, cookies can store only strings. The cookies are concatenated into one semicolon-separated string, and they are sent in the cookie header of the request. You can set many attributes for every cookie, such as expiration, allowed domains, allowed pages, and many more.

In the examples, I show how to manipulate the cookies through the client-side, but it’s also possible to change them in your server-side application.

CodePen Embed Fallback

Saving the user’s preferences in a cookie can be a good fit if the server can utilize it somehow. For example, in the theme use case, the server can deliver the relevant CSS file and reduce potential bundle size (in case we’re doing server-side-rendering). Another use case might be to share these preferences across multiple subdomain apps without a database.

Reading and writing cookies with JavaScript is not as straightforward as you might think. To save a new cookie, you need to set document.cookie — check out the save function in the example above. I set the dark_theme cookie and add it a max-age attribute to make sure it will not expire when the tab is closed. Also, I add the SameSite and Secure attributes. These are necessary because CodePen uses iframe to run the examples, but you will not need them in most cases. Reading a cookie requires parsing the cookie string.

A cookie string looks like this:

key1=value1;key2=value2;key3=value3

So, first, we have to split the string by semicolon. Now, we have an array of cookies in the form of key1=value1, so we need to find the right element in the array. In the end, we split by the equal sign and get the last element in the new array. A bit tedious, but once you implement the getCookie function (or copy it from my example :P) you can forget it.

Saving application data in a cookie can be a bad idea! It will drastically increase the request size and will reduce application performance. Also, the server cannot benefit from this information as it’s a stale version of the information it already has in its database. If you use cookies, make sure to keep them small.

The pagination example is also not a good fit for cookies, just like localStorage and IndexedDB. The current page is a temporary state that we would like to share with others, and any of these methods do not achieve it.

URL storage

URL is not a storage, per se, but it’s a great way to create a shareable state. In practice, it means adding query parameters to the current URL that can be used to recreate the current state. The best example would be search queries and filters. If we search the term flexbox on CSS-Tricks, the URL will be updated to https://css-tricks.com/?s=flexbox. See how easy it is to share a search query once we use the URL? Another advantage is that you can simply hit the refresh button to get newer results of your query or even bookmark it.

We can save only strings in the URL, and its maximum length is limited, so we don’t have so much space. We will have to keep our state small. No one likes long and intimidating URLs.

Again, CodePen uses iframe to run the examples, so you cannot see the URL actually changing. Worry not, because all the bits and pieces are there so you can use it wherever you want.

CodePen Embed Fallback

We can access the query string through window.location.search and, lucky us, it can be parsed using the URLSearchParams class. No need to apply any complex string parsing anymore. When we want to read the current value, we can use the get function. When we want to write, we can use set. It’s not enough to only set the value; we also need to update the URL. This can be done using history.pushState or history.replaceState, depending on the behavior we want to accomplish.

I wouldn’t recommend saving a user’s preferences in the URL as we will have to add this state to every URL the user visits, and we cannot guarantee it; for example, if the user clicks on a link from Google Search.

Just like cookies, we cannot save application data in the URL as we have minimal space. And even if we did manage to store it, the URL will be long and not inviting to click. Might look like a phishing attack of sorts.

CodePen Embed Fallback

Just like our pagination example, the temporary application state is the best fit for the URL query string. Again, you cannot see the URL changes, but the URL updates with the ?page=x query parameter every time you click on a page. When the web page loads, it looks for this query parameter and fetches the right page accordingly. Now we can share this URL with our friends so they can enjoy our favorite Pokémon.

Cache API

Cache API is a storage for the network level. It is used to cache network requests and their responses. The Cache API fits perfectly with service workers. A service worker can intercept every network request, and using the Cache API, it can easily cache both the requests. The service worker can also return an existing cache item as a network response instead of fetching it from the server. By doing so, you can reduce network load times and make your application work even when offline. Originally, it was created for service workers but in modern browsers the Cache API is available also in window, iframe, and worker contexts as-well. It’s a very powerful API that can improve drastically the application user experience.

Just like IndexedDB the Cache API storage is not limited and you can store hundreds of megabytes and even more if you need to. The API is asynchronous so it will not block your main thread. And it’s accessible through the global property caches.

To read more about the Cache API, the Google Chrome team has made a great tutorial.

Chris created an awesome Pen with a practical example of combining service workers and the Cache API.

Bonus: Browser extension

If you build a browser extension, you have another option to store your data. I discovered it while working on my extension, daily.dev. It’s available via chrome.storage or browser.storage, if you use Mozilla’s polyfill. Make sure to request a storage permission in your manifest to get access.

There are two types of storage options, local and sync. The local storage is self-explanatory; it means it isn’t shared and kept locally. The sync storage is synced as part of the Google account and anywhere you install the extension with the same account this storage will be synced. Pretty cool feature if you ask me. Both have the same API so it’s super easy to switch back-and-forth, if needed. It’s async storage so it doesn’t block the main thread like localStorage. Unfortunately, I cannot create a demo for this storage option as it requires a browser extension but it’s pretty simple to use, and almost like localStorage. For more information about the exact implementation, refer to Chrome docs.

Conclusion

The browser has many options we can utilize to store our data. Following the Chrome team’s advice, our go-to storage should be IndexedDB. It’s async storage with enough space to store anything we want. localStorage is not encouraged, but is easier to use than IndexedDB. Cookies are a great way to share the client state with the server but are mostly used for authentication.

If you want to create pages with a shareable state such as a search page, use the URL’s query string to store this information. Lastly, if you build an extension, make sure to read about chrome.storage.


The post A Primer on the Different Types of Browser Storage appeared first on CSS-Tricks.

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

xm

Post pobrano z: xm

This is a neat little HTML preprocessor from Giuseppe Gurgone. It has very few features, but one of them is HTML includes, which is something I continue to be baffled that HTML doesn’t support natively. There are loads of ways to handle it. I think it’s silly that it’s been consistently needed for decades and HTML could evolve to support it but hasn’t. So anyway, enter another option for handling it.

📢 Today I am open sourcing ✨ ₪ xm ✨ a tiny compiler for HTML that adds support for

imports
slots & fills
a portal to markdown

🔗 https://t.co/mhrlVGg3Wp
⌨️ npm i -g xm && xm dev pic.twitter.com/pYN9RpodsW

— Giuseppe (@giuseppegurgone) September 15, 2020

What is extra neat is that it’s not just includes, but templating with includes in a really clean way. If this was Nunjucks, they solve that by creating a template.njk like…

{% block header %}
  This is the default (overridable) header.
{% endblock %}
<footer>
  {% block footer %}
    This is the default (overridable) footer.
  {% endblock %}
</footer>

And then your actual pages use that template like…

{% extends "parent.html" %}
{% block footer %}
  Special footer for this page.
{% endblock %}

In xm, the syntax stays HTML-y, which is nice. So this template.html

<slot name="header"></slot>
<footer>
  <slot name="footer"></slot>
</footer>

…gets used on a page like this:

<import src="template.html">
  <fill name="header">Custom Header</fill>
  <fill name="footer">
    <p>Custom footer</p>
  </fill>
</import>

Very clean. The additional fact that you can arbitrarily chuck a <markdown> tag anywhere you want and use Markdown within it is extra handy.


The post xm appeared first on CSS-Tricks.

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

How to Think Like a Front-End Developer

Post pobrano z: How to Think Like a Front-End Developer

This is an extended version of my essay “When front-end means full-stack” which was published in the wonderful Increment magazine put out by Stripe. It’s also something of an evolution of a couple other of my essays, “The Great Divide” and “Ooops, I guess we’re full-stack developers now.”

The moment I fell in love with front-end development was when I discovered the style.css file in WordPress themes. That’s where all the magic was (is!) to me. I could (can!) change a handful of lines in there and totally change the look and feel of a website. It’s an incredible game to play.

Back when I was cowboy-coding over FTP. Although I definitely wasn’t using CSS grid!

By fiddling with HTML and CSS, I can change the way you feel about a bit of writing. I can make you feel more comfortable about buying tickets to an event. I can increase the chances you share something with your friends.

That was well before anybody paid me money to be a front-end developer, but even then I felt the intoxicating mix of stimuli that the job offers. Front-end development is this expressive art form, but often constrained by things like the need to directly communicate messaging and accomplish business goals.

Front-end development is at the intersection of art and logic. A cross of business and expression. Both left and right brain. A cocktail of design and nerdery.

I love it.

Looking back at the courses I chose from middle school through college, I bounced back and forth between computer-focused classes and art-focused classes, so I suppose it’s no surprise I found a way to do both as a career.

The term “Front-End Developer” is fairly well-defined and understood. For one, it’s a job title. I’ll bet some of you literally have business cards that say it on there, or some variation like: “Front-End Designer,” “UX Developer,” or “UI Engineer.” The debate around what those mean isn’t particularly interesting to me. I find that the roles are so varied from job-to-job and company-to-company that job titles will never be enough to describe things. Getting this job is more about demonstrating you know what you’re doing more than anything else¹.

Chris Coyier
Front-End Developer

The title variations are just nuance. The bigger picture is that as long as the job is building websites, front-enders are focused on the browser. Quite literally:

  • front-end = browsers
  • back-end = servers

Even as the job has changed over the decades, that distinction still largely holds.

As “browser people,” there are certain truths that come along for the ride. One is that there is a whole landscape of different browsers and, despite the best efforts of standards bodies, they still behave somewhat differently. Just today, as I write, I dealt with a bug where a date string I had from an API was in a format such that Firefox threw an error when I tried to use the .toISOString() JavaScript API on it, but was fine in Chrome. That’s just life as a front-end developer. That’s the job.

Even across that landscape of browsers, just on desktop computers, there is variance in how users use that browser. How big do they have the window open? Do they have dark mode activated on their operating system? How’s the color gamut on that monitor? What is the pixel density? How’s the bandwidth situation? Do they use a keyboard and mouse? One or the other? Neither? All those same questions apply to mobile devices too, where there is an equally if not more complicated browser landscape. And just wait until you take a hard look at HTML emails.

That’s a lot of unknowns, and the answers to developing for that unknown landscape is firmly in the hands of front-end developers.

Into the unknoooooowwwn. – Elsa

The most important aspect of the job? The people that use these browsers. That’s why we’re building things at all. These are the people I’m trying to impress with my mad CSS skills. These are the people I’m trying to get to buy my widget. Who all my business charts hinge upon. Who’s reaction can sway my emotions like yarn in the breeze. These users, who we put on a pedestal for good reason, have a much wider landscape than the browsers do. They speak different languages. They want different things. They are trying to solve different problems. They have different physical abilities. They have different levels of urgency. Again, helping them is firmly in the hands of front-end developers. There is very little in between the characters we type into our text editors and the users for whom we wish to serve.

Being a front-end developer puts us on the front lines between the thing we’re building and the people we’re building it for, and that’s a place some of us really enjoy being.

That’s some weighty stuff, isn’t it? I haven’t even mentioned React yet.

The “we care about the users” thing might feel a little precious. I’d think in a high functioning company, everyone would care about the users, from the CEO on down. It’s different, though. When we code a <button>, we’re quite literally putting a button into a browser window that users directly interact with. When we adjust a color, we’re adjusting exactly what our sighted users see when they see our work.

That’s not far off from a ceramic artist pulling a handle out of clay for a coffee cup. It’s applying craftsmanship to a digital experience. While a back-end developer might care deeply about the users of a site, they are, as Monica Dinculescu once told me in a conversation about this, “outsourcing that responsibility.”


We established that front-end developers are browser people. The job is making things work well in browsers. So we need to understand the languages browsers speak, namely: HTML, CSS, and JavaScript². And that’s not just me being some old school fundamentalist; it’s through a few decades of everyday front-end development work that knowing those base languages is vital to us doing a good job. Even when we don’t work directly with them (HTML might come from a template in another language, CSS might be produced from a preprocessor, JavaScript might be mostly written in the parlance of a framework), what goes the browser is ultimately HTML, CSS, and JavaScript, so that’s where debugging largely takes place and the ability of the browser is put to work.

CSS will always be my favorite and HTML feels like it needs the most love — but JavaScript is the one we really need to examine The last decade has seen JavaScript blossom from a language used for a handful of interactive effects to the predominant language used across the entire stack of web design and development. It’s possible to work on websites and writing nothing but JavaScript. A real sea change.

JavaScript is all-powerful in the browser. In a sense, it supersedes HTML and CSS, as there is nothing either of those languages can do that JavaScript cannot. HTML is parsed by the browser and turned into the DOM, which JavaScript can also entirely create and manipulate. CSS has its own model, the CSSOM, that applies styles to elements in the DOM, which JavaScript can also create and manipulate.

This isn’t quite fair though. HTML is the very first file that browsers parse before they do the rest of the work needed to build the site. That firstness is unique to HTML and a vital part of making websites fast.

In fact, if the HTML was the only file to come across the network, that should be enough to deliver the basic information and functionality of a site.

That philosophy is called Progressive Enhancement. I’m a fan, myself, but I don’t always adhere to it perfectly. For example, a <form> can be entirely functional in HTML, when it’s action attribute points to a URL where the form can be processed. Progressive Enhancement would have us build it that way. Then, when JavaScript executes, it takes over the submission and has the form submit via Ajax instead, which might be a nicer experience as the page won’t have to refresh. I like that. Taken further, any <button> outside a form is entirely useless without JavaScript, so in the spirit of Progressive Enhancement, I should wait until JavaScript executes to even put that button on the page at all (or at least reveal it). That’s the kind of thing where even those of us with the best intentions might not always toe the line perfectly. Just put the button in, Sam. Nobody is gonna die.

JavaScript’s all-powerfulness makes it an appealing target for those of us doing work on the web — particularly as JavaScript as a language has evolved to become even more powerful and ergonomic, and the frameworks that are built in JavaScript become even more-so. Back in 2015, it was already so clear that JavaScript was experiencing incredible growth in usage, Matt Mullenweg, co-founder of WordPress, gave the developer world homework: “Learn JavaScript Deeply”³. He couldn’t have been more right. Half a decade later, JavaScript has done a good job of taking over front-end development. Particularly if you look at front-end development jobs.

While the web almanac might show us that only 5% of the top-zillion sites use React compared to 85% including jQuery, those numbers are nearly flipped when looking around at front-end development job requirements.

I’m sure there are fancy economic reasons for all that, but jobs are as important and personal as it gets for people, so it very much matters.


So we’re browser people in a sea of JavaScript building things for people. If we take a look at the job at a practical day-to-day tasks level, it’s a bit like this:

  • Translate designs into code
  • Think in terms of responsive design, allowing us to design and build across the landscape of devices
  • Build systemically. Construct components and patterns, not one-offs.
  • Apply semantics to content
  • Consider accessibility
  • Worry about the performance of the site. Optimize everything. Reduce, reuse, recycle.

Just that first bullet point feels like a college degree to me. Taken together, all of those points certainly do.

This whole list is a bit abstract though, so let’s apply it to something we can look at. What if this website was our current project?

Our brains and fingers go wild!

  • Let’s build the layout with CSS grid. 
  • What fonts are those? Do we need to load them in their entirety or can we subset them? What happens as they load in? This layout feels like it will really suffer from font-shifting jank. 
  • There are some repeated patterns here. We should probably make a card design pattern. Every website needs a good card pattern. 
  • That’s a gorgeous color scheme. Are the colors mathematically related? Should we make variables to represent them individually or can we just alter a single hue as needed? Are we going to use custom properties in our CSS? Colors are just colors though, we might not need the cascading power of them just for this. Should we just use Sass variables? Are we going to use a CSS preprocessor at all?
  • The source order is tricky here. We need to order things so that they make sense for a screen reader user. We should have a meeting about what the expected order of content should be, even if we’re visually moving things around a bit with CSS grid.
  • The photographs here are beautifully shot. But some of them match the background color of the site… can we get away with alpha-transparent PNGs here? Those are always so big. Can any next-gen formats help us? Or should we try to match the background of a JPG with the background of the site seamlessly. Who’s writing the alt text for these?
  • There are some icons in use here. Inline SVG, right? Certainly SVG of some kind, not icon fonts, right? Should we build a whole icon system? I guess it depends on how we’re gonna be building this thing more broadly. Do we have a build system at all?
  • What’s the whole front-end plan here? Can I code this thing in vanilla HTML, CSS, and JavaScript? Well, I know I can, but what are the team expectations? Client expectations? Does it need to be a React thing because it’s part of some ecosystem of stuff that is already React? Or Vue or Svelte or whatever? Is there a CMS involved?
  • I’m glad the designer thought of not just the “desktop” and “mobile” sizes but also tackled an in-between size. Those are always awkward. There is no interactivity information here though. What should we do when that search field is focused? What gets revealed when that hamburger is tapped? Are we doing page-level transitions here?

I could go on and on. That’s how front-end developers think, at least in my experience and in talking with my peers.

A lot of those things have been our jobs forever though. We’ve been asking and answering these questions on every website we’ve built for as long as we’ve been doing it. There are different challenges on each site, which is great and keeps this job fun, but there is a lot of repetition too.

Allow me to get around to the title of this article. 

While we’ve been doing a lot of this stuff for ages, there is a whole pile of new stuff we’re starting to be expected to do, particularly if we’re talking about building the site with a modern JavaScript framework. All the modern frameworks, as much as they like to disagree about things, agree about one big thing: everything is a component. You nest and piece together components as needed. Even native JavaScript moves toward its own model of Web Components.

I like it, this idea of components. It allows you and your team to build the abstractions that make the most sense to you and what you are building.

Your Card component does all the stuff your card needs to do. Your Form component does forms how your website needs to do forms. But it’s a new concept to old developers like me. Components in JavaScript have taken hold in a way that components on the server-side never did. I’ve worked on many a WordPress website where the best I did was break templates into somewhat arbitrary include() statements. I’ve worked on Ruby on Rails sites with partials that take a handful of local variables. Those are useful for building re-usable parts, but they are a far cry from the robust component models that JavaScript frameworks offer us today.

All this custom component creation makes me a site-level architect in a way that I didn’t use to be. Here’s an example. Of course I have a Button component. Of course I have an Icon component. I’ll use them in my Card component. My Card component lives in a Grid component that lays them out and paginates them. The whole page is actually built from components. The Header component has a SearchBar component and a UserMenu component. The Sidebar component has a Navigation component and an Ad component. The whole page is just a special combination of components, which is probably based on the URL, assuming I’m all-in on building our front-end with JavaScript. So now I’m dealing with URLs myself, and I’m essentially the architect of the entire site. [Sweats profusely]

Like I told ya, a whole pile of new responsibility.

Components that are in charge of displaying content are almost certainly not hard-coded with data in them. They are built to be templates. They are built to accept data and construct themselves based on that data. In the olden days, when we were doing this kind of templating, the data has probably already arrived on the page we’re working on. In a JavaScript-powered app, it’s more likely that that data is fetched by JavaScript. Perhaps I’ll fetch it when the component renders. In a stack I’m working with right now, the front end is in React, the API is in GraphQL and we use Apollo Client to work with data. We use a special “hook” in the React components to run the queries to fetch the data we need, and another special hook when we need to change that data. Guess who does that work? Is it some other kind of developer that specializes in this data layer work? No, it’s become the domain of the front-end developer.

Speaking of data, there is all this other data that a website often has to deal with that doesn’t come from a database or API. It’s data that is really only relevant to the website at this moment in time.

  • Which tab is active right now?
  • Is this modal dialog open or closed?
  • Which bar of this accordion is expanded?
  • Is this message bar in an error state or warning state?
  • How many pages are you paginated in?
  • How far is the user scrolled down the page?

Front-end developers have been dealing with that kind of state for a long time, but it’s exactly this kind of state that has gotten us into trouble before. A modal dialog can be open with a simple modifier class like <div class="modal is-open"> and toggling that class is easy enough with .classList.toggle(".is-open"); But that’s a purely visual treatment. How does anything else on the page know if that modal is open or not? Does it ask the DOM? In a lot of jQuery-style apps of yore, yes, it would. In a sense, the DOM became the “source of truth” for our websites. There were all sorts of problems that stemmed from this architecture, ranging from a simple naming change destroying functionality in weirdly insidious ways, to hard-to-reason-about application logic making bug fixing a difficult proposition.

Front-end developers collectively thought: what if we dealt with state in a more considered way? State management, as a concept, became a thing. JavaScript frameworks themselves built the concept right in, and third-party libraries have paved and continue to pave the way. This is another example of expanding responsibility. Who architects state management? Who enforces it and implements it? It’s not some other role, it’s front-end developers.

There is expanding responsibility in the checklist of things to do, but there is also work to be done in piecing it all together. How much of this state can be handled at the individual component level and how much needs to be higher level? How much of this data can be gotten at the individual component level and how much should be percolated from above? Design itself comes into play. How much of the styling of this component should be scoped to itself, and how much should come from more global styles?

It’s no wonder that design systems have taken off in recent years. We’re building components anyway, so thinking of them systemically is a natural fit.

Let’s look at our design again:

A bunch of new thoughts can begin!

  • Assuming we’re using a JavaScript framework, which one? Why? 
  • Can we statically render this site, even if we’re building with a JavaScript framework? Or server-side render it? 
  • Where are those recipes coming from? Can we get a GraphQL API going so we can ask for whatever we need, whenever we need it?
  • Maybe we should pick a CMS that has an API that will facilitate the kind of front-end building we want to do. Perhaps a headless CMS?
  • What are we doing for routing? Is the framework we chose opinionated or unopinionated about stuff like this?
  • What are the components we need? A Card, Icon, SearchForm, SiteMenu, Img… can we scaffold these out? Should we start with some kind of design framework on top of the base framework?
  • What’s the client state we might need? Current search term, current tab, hamburger open or not, at least.
  • Is there a login system for this site or not? Are logged in users shown anything different? 
  • Is there are third-party componentry we can leverage here?
  • Maybe we can find one of those fancy image components that does blur-up loading and lazy loading and all that.

Those are all things that are in the domain of front-end developers these days, on top of everything that we already need to do. Executing the design, semantics, accessibility, performance… that’s all still there. You still need to be proficient in HTML, CSS, JavaScript, and how the browser works. Being a front-end developer requires a haystack of skills that grows and grows. It’s the natural outcome of the web getting bigger. More people use the web and internet access grows. The economy around the web grows. The capability of browsers grows. The expectations of what is possible on the web grows. There isn’t a lot shrinking going on around here.

We’ve already reached the point where most front-end developers don’t know the whole haystack of responsibilities. There are lots of developers still doing well for themselves being rather design-focused and excelling at creative and well-implemented HTML and CSS, even as job posts looking for that dwindle.

There are systems-focused developers and even entire agencies that specialize in helping other companies build and implement design systems. There are data-focused developers that feel most at home making the data flow throughout a website and getting hot and heavy with business logic. While all of those people might have “front-end developer” on their business card, their responsibilities and even expectations of their work might be quite different. It’s all good, we’ll find ways to talk about all this in time.

In fact, how we talk about building websites has changed a lot in the last decade. Some of my early introduction to web development was through WordPress. WordPress needs a web server to run, is written in PHP, and stores it’s data in a MySQL database. As much as WordPress has evolved, all that is still exactly the same. We talk about that “stack” with an acronym: LAMP, or Linux, Apache, MySQL and PHP. Note that literally everything in the entire stack consists of back-end technologies. As a front-end developer, nothing about LAMP is relevant to me.

But other stacks have come along since then. A popular stack was MEAN (Mongo, Express, Angular and Node). Notice how we’re starting to inch our way toward more front-end technologies? Angular is a JavaScript framework, so as this stack gained popularity, so too did talking about the front-end as an important part of the stack. Node and Express are both JavaScript as well, albeit the server-side variant.

The existence of Node is a huge part of this story. Node isn’t JavaScript-like, it’s quite literally JavaScript. It makes a front-end developer already skilled in JavaScript able to do server-side work without too much of a stretch.

“Serverless” is a much more modern tech buzzword, and what it’s largely talking about is running small bits of code on cloud servers. Most often, those small bits of code are in Node, and written by JavaScript developers. These days, a JavaScript-focused front-end developer might be writing their own serverless functions and essentially being their own back-end developer. They’ll think of themselves as full-stack developers, and they’ll be right.

Shawn Wang coined a term for a new stack this year: STAR or Design System, TypeScript, Apollo, and React. This is incredible to me, not just because I kind of like that stack, but because it’s a way of talking about the stack powering a website that is entirely front-end technologies. Quite a shift.

I apologize if I’ve made you feel a little anxious reading this. If you feel like you’re behind in understanding all this stuff, you aren’t alone.

In fact, I don’t think I’ve talked to a single developer who told me they felt entirely comfortable with the entire world of building websites. Everybody has weak spots or entire areas where they just don’t know the first dang thing. You not only can specialize, but specializing is a pretty good idea, and I think you will end up specializing to some degree whether you plan to or not. If you have the good fortune to plan, pick things that you like. You’ll do just fine.

The only constant in life is change.

– Heraclitus
    – Motivational Poster
        – Chris Coyier


¹ I’m a white dude, so that helps a bunch, too. ↩️
² Browsers speak a bunch more languages. HTTP, SVG, PNG… The more you know the more you can put to work! ↩️
³ It’s an interesting bit of irony that WordPress websites generally aren’t built with client-side JavaScript components. ↩️


The post How to Think Like a Front-End Developer appeared first on CSS-Tricks.

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

How to Make Stars in Photoshop

Post pobrano z: How to Make Stars in Photoshop

Final product image
What You’ll Be Creating

Ever wondered how to make stars in Adobe Photoshop? Well, wonder no more! In this quick tip tutorial, you will learn how to make stars in Photoshop quickly and easily.  

For more quick tips, visit us at the Envato Tuts+ YouTube Channel:

What You’ll Learn in This Photoshop Tutorial

  • How to make a star in Adobe Photoshop
  • How to create a star effect in Adobe Photoshop
  • How to make star trails with a brush
  • How to create a shining star
  • How to create a shooting star

Tutorial Assets

For this tutorial, I will be using stock photos from Envato Elements:

1. How to Make a Star in Adobe Photoshop

Step 1

In your document, go to the Polygon Menu, right-click on it, and select the Polygon Tool (U), which is a pentagon.

Polygon Tool U For Star Shape

Step 2

Go to the Settings in the top toolbar. This will be shaped like a cog. Click on this and select the Star checkbox with the Radius set to 25%.

Path Options for Star Shape

Step 3

Next, drag out your shape. This will give us a chunky star.

25 Star Sample

Step 4

Change the percentage to create a range of different star shapes. Simple! 

Star Path Option Percentages

2. How to Create a Star Effect in Adobe Photoshop

Step 1

Create a New Layer (Control-N) in your document and fill the layer with black.

Base Image for Star Effect in Photoshop

Step 2

Next, go to Filter > Add Noise and set the Amount to 50%, select Gaussian, and check the Monochromatic box. Click OK.

Noise Filter for Star Effect in Photoshop

Step 3

Go to Filter >Blur > Gaussian Blur and set the blur Radius to 1.5%, and click OK.

Gaussian Blur for Star Effect in Photoshop

Step 4

Next, we go to Levels (Control-L) and move the arrows to the base of the curve in the Input Levels, similar to how this is below. Play with these sliders until you get a pleasing star field intensity.

Levels for Star Effect in Photoshop

Step 5

Next, set the Layer Blend Mode to Screen. To add extra intensity to your stars, simply duplicate the layer. I think this makes a really impressive star effect with not much effort.

Star Effect Final Result

3. How to Make Star Trails With a Brush

Step 1

Create a star of your choosing as in „Part 1. How to Make a Star in Adobe Photoshop”, and make sure that it’s set to black.

Here are the settings I used to create a star trail.

Brush Tip Shape 

  • Spacing to 102%

Shape Dynamics 

  • Size Jitter to 27% with Control set to Pen Pressure
  • Angle Jitter at 70% with the Control set to Pen Pressure
  • Roundness Jitter to 20%; Control: Off
  • Minimum Roundness to 25%

Scattering 

  • Scatter is set to 196% on Both Axes; Control: Pen Pressure 
  • Count Jitter to 14%; ControlPen Pressure 

Transfer

  • Opacity Jitter is set to 0%; Pen Pressure is set to Minimum 0%
  • Flow Jitter at 0% set to Pen Pressure with Minimum at 76%

Smoothing

  • On 
Star Brush Base for Star Trail Brush Effect in Photoshop

Step 2

Now you can save your brush by clicking the square with the + sign at the bottom of the Brush Settings panel.

Saving for Star Trail Brush Effect in Photoshop

Step 3

Here’s how our star trail brush looks with our settings. 

Sample for Star Trail Brush Effect in Photoshop

4. How to Create a Shining Star

Step 1

Draw out your stars using the Star Trail Brush we just created and duplicate the layer.

Glowing Star Trail Effect in Photoshop Base

Step 2

On the lower layer, go to Filter > Blur > Gaussian Blur and set the Radius to 8.6 Pixels. Click OK.

Glowing Star Trail Effect in Photoshop Glow

5. How to Create a Shooting Star

Step 1

In the Brush Settings, select the default Hard Round Pressure Opacity brush and squeeze the tip shape to a narrow oval.

Brush settings for Shooting Star Effect in Photoshop

Step 2

On a New Layer (Control-N), draw out a shooting star with the tip being more intense than the trail.

Base for Shooting Star Effect in Photoshop

Step 3

Select the Eraser (E) and use a Soft Brush to gently paint out some of the tail.

Refining Shooting Star Effect in Photoshop

Step 4

To create a meteor shower effect, hold Alt and use the Move Tool (V) to duplicate each layer. Scale, move, and repeat as necessary. Optionally, to add depth, you can lower the opacity of some of the shooting stars. 

Meteor Shower Shooting Star Effect in Photoshop

Conclusion

Now you have learned how to make stars in Photoshop! I hope you found this quick tip useful and can use these techniques to jazz up your artwork. 

How to Make Stars in Photoshop Sample Image

If you’d like to learn more from Envato Tuts+, here are some excellent tutorials on how to get started with Adobe Photoshop, working with brushes and light effects!

How to Create an Inspirational Vector Political Poster

Post pobrano z: How to Create an Inspirational Vector Political Poster

Final product image
What You’ll Be Creating

Learn how to create a Shepard Fairey Photoshop effect with the help of Illustrator with this poster tutorial. 

This tutorial is inspired by Shepard Fairey’s famous political poster series for the Obama Democratic Party campaign in the US in 2004 and now being recreated for the Time magazine cover for November 2020, month of the US Election. 

We’ll be showing you how to create this style of design. We’ll start with basic image editing techniques in Adobe Photoshop to get our guide layers setup, and then we’ll jump into Adobe Illustrator. You don’t need any fancy equipment to do this. I used an older mouse that still has the rubber ball.

Note: This tutorial has been recently updated, however the stock image and pattern are no longer available for download. Please find the appropriate items to replace them to complete the exact end result. Envato Tuts+ does not endorse any political party in the publishing of this tutorial. Rather, this tutorial is focused on demonstrating a workflow for recreating this iconic poster.


Create the Hope Photo Effect in Seconds!

Want to save time and get a Photoshop action which will create the Hope photo effect in seconds? With this Obama Hope Poster Generator Photoshop Action from Envato Elements.

Hope Photo Effect Photoshop Action

1. Crop and Modify Your Stock Image

Step 1

For this effect it is best to have a portrait style picture, preferably of a subject that appears to be thinking, or looking off into the distance. 

Political Poster Tutorial

Step 2

Once you have your image, you need to Open it in Photoshop and Crop it appropriately. The top of the image should be cropped to the top of your subject’s head, and the bottom should be a bit higher than chest height. The crop should have about a 2:1 ratio.

Political Poster Tutorial

Step 3

Now we need to Posterize the image. Go to Image > Adjustments > Posterize. An appropriate posterization level for the look we are going for is 5.

Political Poster Tutorial

Step 4

Now we’re going to create our guide layers for use in Illustrator. Start by duplicating your posterized layer, and name this new layer „Pattern Guide.” Then go to Image > Adjustments > Threshold. We’re going to slide our Point until we get something similar to below. We want it fairly dark, but still with a small amount of detail. Also, when using Threshold, it is best to use the Peaks that you see.

Political Poster Tutorial

Step 5

Save this newly created layer as „patternguide.psd,” or something similar, as you’ll need it for Illustrator.

Political Poster Tutorial

Step 6

We need to repeat Step 4 and Step 5 three more times. Each time apply a lower threshold, and save each new layer. Below are the settings I used, again notice the peaks.

Political Poster Tutorial

2. Setup Your Document and Palettes

Step 1

Before we start to outline our layers, we need to create the horizontal blue line pattern. To do this create a new Illustrator document. Give it a Height and Width of 4px. Then create a rectangle filled with our light blue color (#4F919F), and cover the top half of the canvas.

Political Poster Tutorial

Step 2

Cover the bottom half with a rectangle filled with beige. Then Select All (Control + A), and drag this over to our Swatches panel. Congratulations you’ve made a pattern!

Political Poster Tutorial

Step 3

Now we have to save this Swatch set so we can use it in our poster we’re about to make. In the bottom left corner of our Swatches panel we’ll select Save Swatches from the Swatches Library Menu. Name it anything you want, I used „pattern.” You can now close this document, as we won’t need it anymore.

Political Poster Tutorial

Step 4

Here is the color palette we’ll be using for this tutorial. There are four colors and a pattern. We’ll be using a mix of beige and light blue colors.

Political Poster Tutorial

3. Create Your Portrait

Step 1

Now that we have our reference images and pattern created, it is time to create a New document in Illustrator. I used a canvas size of 700 x 850px.

Political Poster Tutorial

Step 2

We’re going to start with our darkest guide layer, this will be our pattern layer. We’re going to outline the layer using the Pen Tool (P). So to start we’re going to go to File > Place and select our first reference layer into Illustrator. If you’ve been following verbatim, this file to place is called „patternguide.psd”.

Political Poster Tutorial

Step 3

Let’s stop for a moment and discuss the proper use of the Pen Tool (P) in Illustrator. This is one area where Illustrator handedly trumps Photoshop, but only if you use it correctly.

For any curve you basically have three clicks; two are anchor points, and the other is your curve point. You place your curve point at the highest point of your curve. You place the anchors at where the curve starts and ends.

One click is all that is needed when you are creating a curve. You can then change the curve points to curves after you have done the entire shape. To convert them use the Direct Selection Tool (A) and click on the Convert Selected Anchor Points to Smooth icon.

Political Poster Tutorial

Step 4

Before we can outline our first layer, we need to load our pattern into the Swatches Library. To do this select Other Library from the Swatches Library menu in the Swatches panel.

Political Poster Tutorial

Step 5

Okay, so back to outlining our first layer. Create New Layer below the file you just placed into Illustrator. This layer will hold our outline. We place it below because it is easier to see what we’re outlining that way.

Now we grab our Pen Tool (P), give it a stroke of null, and a fill of our pattern. Then start outlining all the black areas with the Pen Tool (P). The key is to average it out, don’t follow too closely to the guide layer. Just roughly outline, and don’t worry about our curves, as we’ll fix that after we create our outline.

Note: This is the most tedious part of the process.

Political Poster Tutorial

Step 6

You might have noticed that there are portions in the middle that are lighter that we just went right over with outlines. Well we’re going to fix that by outlining those using the same process. Fill those with our beige color, as shown below. We’ll do this on a new layer just above the pattern layer. After you’ve done that, you should have something similar to the following.

Political Poster Tutorial

Step 7

Now we smooth out the shapes we just created. We want most of our points to be smooth, but I find it looks better if you leave a few the way they are. View the effect below from smoothing both the pattern and beige layer.

Note: I made this image out of order and the pattern was wrong, don’t worry about the color difference.

Political Poster Tutorial

Step 8

Now we just do this same thing for each layer. Roughly outlining it, then outlining the highlights with the color immediately below it, and then smoothing out our outlines. The next layer should have solid light blue, followed by red, and then finally our dark blue.

Political Poster Tutorial

Step 9

Okay, you should have something like the following. The tedious part is over. Now to make it look like a poster. First we’ll put a beige filled rectangle below all these layers, this will serve as our background.

Political Poster Tutorial

Step 10

Now we’ll need to put our red and light blue halves in. We’re going to do this just above the beige rectangle layer. Use the Rectangle Tool (M) to place the two rectangles.

Political Poster Tutorial

Step 11

Our poster is looking pretty good. Let’s create the space needed to add the inspiring text at the bottom. You’ll probably have to enlarge your canvas area. To do this go to File > Document Setup. I added 300px onto mine.

Political Poster Tutorial

Step 12

Now extend you beige rectangle so that it covers the new length of your canvas. Then create a new rectangle filled with our dark blue color. It should be a quarter the size of main subject.

Political Poster Tutorial

Step 13

Time to add our inspiring word. We’ll use light blue for the font color, and we want to change the text settings so that the word fills most of the dark blue rectangle. To change the spacing between the characters, use the Character panel. This is available to us when we are using the Text Tool (T). I used the font „Myriad Pro”.

Political Poster Tutorial

Step 14

Almost finished, we need to clean up our borders a little bit. First, select every layer, but your beige layer. Then create a Group (Control + G). Then Vertically and Horizontally Align them to the artboard.

Political Poster Tutorial

Step 15

Now we’re going to clean up the edges of our poster. Cover the layers that we grouped in a rectangle of any color. Then use the Pathfinder panel, and select Subtract Shape From Area.

Political Poster Tutorial

Awesome Work! You’re Now Finished!

Way to go, we’re done! We managed to create a really awesome effect without needing a whole lot of artistic ability. We also learned how to efficiently use the Pen Tool, and a nice way to use Photoshop and Illustrator in tandem. This is my first tutorial, so I’m sure there will be questions. Feel free to ask in the comments, and I’ll try and answer as quickly as I can. Thanks!

Political Poster Tutorial

Want to Learn More?

Check out the following great poster design tutorials to learn more:

How Artists Make a Living With Patreon

Post pobrano z: How Artists Make a Living With Patreon

„You won’t make any money as an artist.”

„Art is not a career.”

„Get a real job.”

We’ve all heard them before. The 101 reasons why art will never be a sustainable career. But it’s time to throw away all that negativity and pick up some real hope, because the digital age is changing the game for artists.

In today’s world, there are more opportunities than ever which allow artists to do what they love while creating a sustainable income. And if you’re willing to put in the time and work, you too can reap the incredible rewards of this new age in being a creative.

using a graphic tablet
Stock photo: using a graphic tablet (Envato Elements)

Today we’ll dive into one avenue that artists turn to when they want to figure out how illustrators make money online. We’ll take a look at what Patreon is, how to use Patreon as an artist, how to set up an account, look at sites like Patreon, and consider the alternatives to building these types of businesses online.

So let’s get to know more about Patreon.

What Is Patreon?

Creator Jack Conte was looking for a way to support himself and his YouTube channel when he decided to found Patreon. Patreon is a crowdfunding platform that allows creators to fund their projects by fans, or patrons, who donate money on a recurring basis.

How Illustrators Make Money on Patreon

Similar to crowdfunding sites like Kickstarter, Patreon allows users to create their own profiles where fans can support their work, either through pledges of monthly Patreon donations or donations per project.

You can help your favorite Patreon artists hit their goals and be one step closer to supporting their dreams of making a living doing what they love.

Patreon is reinventing the way artists are supported by their community. Pledges are separated into several different tiers, with amazing rewards at each level. And with fans able to pledge as little as $1 per cycle, there’s a real sense that you’re able to support artists without needing to break the bank.

Paid to Do „Nothing?”

So how do you convince people to give you Patreon donations? And are they really okay with it?

Don’t be fooled by the naysayers who don’t understand what it takes to build a business online. The number one misconception you’ll run into is people thinking that you’re getting paid to do nothing.

But let’s be real. Patreon artists by no means are accepting handouts.

And it’s not just a platform for visual artists. Writers, musicians, podcasters, photographers, and creatives of all different shapes and sizes use Patreon to fund their projects. Each of these projects takes from dozens to hundreds of hours to complete, on top of the years of experience put into mastering their craft.

So think of all those years you spent creating for others without ever receiving a single penny. Allow Patreon to buy back those years by supplying you with a way to support yourself reliably.

How Do I Start a Patreon?

Learning how to start a Patreon takes a few simple steps. Let’s walk through them together.

1. Head to the Patreon Website

The first step in learning how to start a Patreon is to head to their website. In the upper right-hand corner, click the red button that says Create on Patreon.

Patreon homepage

2. Choose a Sign-Up Option

You’ll find three sign-up options: Sign up with Google, Sign up with Facebook, and the choice to create an account without linking.

Signup options

What’s the difference? Choosing either of the first two sign-up options will link your Patreon account to Google or Facebook, meaning you won’t need to make new login information. However, that does mean that if you lose your Google or Facebook account, you lose your Patreon account too.

3. Complete the Account Creation Steps

Once you’ve signed up, you’ll be greeted with five steps to get your account ready.

Choose Content Categories

On Patreon, you can promote anime, podcasts, films, and other creative arts. You can choose up to two categories from the list to describe the content you’ll show on your Patreon.

How Do I Start a Patreon Tutorial Content Categories

18+ Age Filter

This is an important step for Patreon artists. Patrons on Patreon come from many different age groups. If you have content that’s appropriate for older audiences and not for younger ones, this will add an 18+ pop up to visitors of your page.

How To Start a Patreon Tutorial Age Filter

Currency Options

Patreon offers three payout currency options to creators: US Dollars, Euro, or British Pounds.

How Do I Start a Patreon Tutorial Select Currency

Don’t worry. Even if you don’t see your local currency, you can still create on Patreon! This article from the Patreon Help Center addresses how you can receive payouts if you’re not based in the United States, United Kingdom, or Europe. 

Offer Exclusive Merch

Part of the appeal of making Patreon art is connecting with patrons, and you can build that relationship with merch. If you choose this option, you design the merch and Patreon will handle production and shipping for an added fee to your membership plan. 

Pro tip: tying merch to different tiers is a great incentive for patrons. Learn about the relationship between tier pricing and merch from the Patreon Help Center.

How to Start a Patreon Tutorial Merch Patreon Reward Ideas for Artists

Merch through Patreon isn’t mandatory. There are plenty of other Patreon reward ideas for artists that you can find to show your patrons love.

Reserve Custom URL

If you want to set up a custom URL for your Patreon page, you can do so here. You’ll need to connect at least one social media account on this page to be able to use this option.

Take this opportunity to connect all your social accounts to your Patreon. This is how to use Patreon as an artist with an interconnected presence.

How to Start a Patreon Tutorial Reserve Custom URL

4. Set Up Account Details and Launch

We’re almost done learning how to start a Patreon! Your last and most important step will be filling out the important account details. This is where you share information about you and what you create, customize tiers, choose merch, edit payment information, and other account information. Note: you won’t be able to launch your Patreon until you finish the required items in the checklist (shown below). 

How Do I Start a Patreon Tutorial Required Checklist

Once you’re finished with this step, click Launch in the upper right-hand corner. 

How Do I Start A Patreon Tutorial Launch Patreon

And you’re done! If you’ve been wondering „how do I start a Patreon”, now you know how quick the process is. 

How to Be Successful With Patreon

Want a look at a day in the life of a creator? Illustrator Andreas Rocha shares the reality of what it takes to become one of the successful Patreon artists. Their insights are useful if you need some Patreon help.

„Posting my work on Patreon is different from posting paintings on my online portfolio. There is not so much freedom as I have to prepare the files and paint following certain guidelines so people can more or less follow what is going on when they watch the videos. I also have to try and find themes that people appreciate and find interesting.

It’s challenging, because ultimately you have to keep motivated to post but that can only work if people support you. If you set pledge levels too high people won’t support you, but if the income is too low it ends up not being rewarding. You must have patience as the number of followers rises, very slowly. My goal with Patreon is to share my workflow with people interested in knowing how I work and, of course, to provide another source of income.”

Art by Patreon Artist Andreas Rocha for Patreon
Patreon Reward, „Fiery Path” by Andreas Rocha.

I asked even more artists about their insight into what it takes to be successful on Patreon. Let’s take a look at what they all have to say.

Set Realistic Goals

As with any project, goals help not only with motivation but establishing what your end game is. And for Patreon donations, goals also allow your fans to help you by understanding what your needs are. Need new equipment? Say it. Looking to make this your full-time job? Be honest. Don’t be afraid to post your real goals while asking for pledges. It’s how illustrators make money from Patreon.

Digital artist DanteWontDie knows all about goal-setting on Patreon. Here is what he had to say:

„I
think Patreon is a place that you need to prove yourself. You have to let people
willingly pledge to see your art. My
page was set up at the beginning of 2015 and I think I’m pretty satisfied with
my monthly income on that, but I’m still far from my ultimate goal ($2000
per month).

I know there’s still a lot of space for me
to improve and I really appreciate those who have already pledged on my page now. Accumulating
Patreon pledges is like setting up your own business. Do you want to be a full-time artist, or just do it for fun? The good thing is you
have almost zero costs, so you can manage your time accordingly.”

Patreon Art by DanteWontDie Patreon Artist
Pharah Reporting, art by DanteWontDie.

Post Regularly

This is one of the most important pieces of Patreon help you’ll get. If you showed up to your work only a few times a week, you wouldn’t have the greatest reputation. So just like any other profession, make sure you’re able to post regularly in order to keep your patrons interested and Patreon donations coming in.

Icarus, artist and creator of the analog scifi comic Inhuman, offer his advice on the best way to approach posting regularly:

„Engage,
engage, engage! Build your brand before launching as much as possible, and then
encourage people to check out your Patreon whenever possible.

Rewards are a
must, if that’s WIPs or access to zips of unreleased art or whatever. People
just like to get „something” for their money besides just the knowledge they’re
helping you. Patreon
is half of our household income, so it helps a lot. More than anything, being friendly in whatever you do also pays!”

Inhuman Patreon Art by Icarus
Inhuman Comic by Icarus.

Offer Valuable Rewards

Though it’s not uncommon that people will support you just for the heck of it, one of the best ways you can keep your patrons happy while garnering new ones is to offer them valuable rewards. This could be Patreon anime commissions, shoutouts, or other rewards.

Freelance Digital Artist Didi Esmeralda offers tutorials and commissions for her patrons depending on the reward tier they select. She reminds us why it’s important to have Patreon reward ideas for artists and to keep in communication with your fans for support:

„Each
artist must divulge their own work on social networks to be appreciated by
followers and fans, and then communicate to their followers that they can
support the work in patreon, and get exclusive content that can be found there.”

Patreon Art by Didi Esmeralda
Patreon commission by Didi Esmeralda.

Alternatives to Patreon

But remember, Patreon is not your only option here. While there are other sites like Patreon, taking advantage of social media and online business goes way beyond just crowdfunding sites. Here are just a few other areas that are some great alternatives to sites like Patreon:

  • Sell products on Envato Market.
  • Open online shops.
  • Stream live for donations.
  • Take on paid commissions.
  • Offer video tutorials and instruction.
  • Offer your services as a consultant or speaker.

Though artist Racheal Scotland is new to building her presence on Patreon, she’s a talented artist with years in the industry. Take it from her on what other sites like Patreon and alternatives you can look to:

If
you’re looking to live off your art, you can open shops on DeviantArtINPRNT, and Etsy. If
you’re confident in your work, open commissions. There’s always
someone who’s bound to help support your work.

As long as you make sure people know where to find your work, market all
your avenues. Create a portfolio. And use all the platforms available to you.

Art by Racheal Scotland
Laughter, art by Racheal Scotland.

Graphic Designer Roberto Blake is not a Patreon artist but definitely knows the online grind. From his popular YouTube channel to his offline speaking engagements, he’s found a way to not only build a community but one that supports his creative endeavors. Here’s his advice:

„A service based business
is not sustainable long term. My variations of diversifying income (advertising/affiliate marketing/public speaking/paid
writing/consulting/webinars) may not be a fit for everyone.
However, creating a product that can generate a combination
of passive and active income can make you more secure.

Envato, for instance,
is a great marketplace and I buy assets to modify to save my time pretty
regularly. Align
your passions to a purpose and the work in between is figuring out a practical
application of it. Making
your moves with intention and clarity makes all the difference in where you end
up.”

Graphic Designs by Roberto Blake
Book cover art by Robert Blake.

Where You Can Find These Artists

Thank you to all the artists who gave their wonderful advice. If you want to learn more about them, feel free to follow their work on social media and support their pages below:

Conclusion

Whether you make Patreon anime or abstract illustrations, there’s an audience out there. If you point them in the right direction, your fans will support you more than you could ever imagine. So take a risk and put yourself out there to build an incredible community that will back your dreams. 

Who knows, maybe with the help of Patreon or other online avenues, you’ll be able to make a living doing what you love. Now that you know how to use Patreon as an artist, it’s time to get started. So how will you put yourself out there today?

If you’re an artist starting out online, you can find more helpful articles and social media graphics from Envato Tuts+ below. Have any experience with Patreon? Let us know how you like it in the comments below.

Create an FAQ Slack app with Netlify functions and FaunaDB

Post pobrano z: Create an FAQ Slack app with Netlify functions and FaunaDB

Sometimes, when you’re looking for a quick answer, it’s really useful to have an FAQ system in place, rather than waiting for someone to respond to a question. Wouldn’t it be great if Slack could just answer these FAQs for us? In this tutorial, we’re going to be making just that: a slash command for Slack that will answer user FAQs. We’ll be storing our answers in FaunaDB, using FQL to search the database, and utilising a Netlify function to provide a serverless endpoint to connect Slack and FaunaDB.

Prerequisites

This tutorial assumes you have the following requirements:

  • Github account, used to log in to Netlify and Fauna, as well as storing our code
  • Slack workspace with permission to create and install new apps
  • Node.js v12

Create npm package

To get started, create a new folder and initialise a npm package by using your package manager of choice and run npm init -y from inside the folder. After the package has been created, we have a few npm packages to install.

Run this to install all the packages we will need for this tutorial:

npm install express body-parser faunadb encoding serverless-http netlify-lambda

These packages are explained below, but if you are already familiar with them, feel free to skip ahead.

Encoding has been installed due to a plugin error occurring in @netlify/plugin-functions-core at the time of writing and may not be needed when you follow this tutorial.

Packages

Express is a web application framework that will allow us to simplify writing multiple endpoints for our function. Netlify functions require handlers for each endpoint, but express combined with serverless-http will allow us to write the endpoints all in one place.

Body-parser is an express middleware which will take care of the application/x-www-form-urlencoded data Slack will be sending to our function.

Faunadb is an npm module that allows us to interact with the database through the FaunaDB Javascript driver. It allows us to pass queries from our function to the database, in order to get the answers

Serverless-http is a module that wraps Express applications to the format expected by Netlify functions, meaning we won’t have to rewrite our code when we shift from local development to Netlify.

Netlify-lambda is a tool which will allow us to build and serve our functions locally, in the same way they will be built and deployed on Netlify. This means we can develop locally before pushing our code to Netlify, increasing the speed of our workflow.

Create a function

With our npm packages installed, it’s time to begin work on the function. We’ll be using serverless to wrap an express app, which will allow us to deploy it to Netlify later. To get started, create a file called netlify.toml, and add the following into it:

[build]
  functions = "functions"

We will use a .gitignore file, to prevent our node_modules and functions folders from being added to git later. Create a file called .gitignore, and add the following:

functions/

node_modules/

We will also need a folder called src, and a file inside it called server.js. Your final file structure should look like:

With this in place, create a basic express app by inserting the code below into server.js:

const express = require("express");
const bodyParser = require("body-parser");
const fauna = require("faunadb");
const serverless = require("serverless-http");
 
const app = express();
 
module.exports.handler = serverless(app);

Check out the final line; it looks a little different to a regular express app. Rather than listening on a port, we’re passing our app into serverless and using this as our handler, so that Netlify can invoke our function.

Let’s set up our body parser to use application/x-www-form-urlencoded data, as well as putting a router in place. Add the following to server.js after defining app: 

const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/.netlify/functions/server", router);

Notice that the router is using /.netlify/functions/server as an endpoint. This is so that Netlify will be able to correctly deploy the function later in the tutorial. This means we will need to add this to any base URLs, in order to invoke the function.

Create a test route

With a basic app in place, let’s create a test route to check everything is working. Insert the following code to create a simple GET route, that returns a simple json object:

router.get("/test", (req, res) => {
 res.json({ hello: "world" });
});

With this route in place, let’s spin up our function on localhost, and check that we get a response. We’ll be using netlify-lambda to serve our app, so that we can imitate a Netlify function locally on port 9000. In our package.json, add the following lines into the scripts section:

"start": "./node_modules/.bin/netlify-lambda serve src",
   "build": "./node_modules/.bin/netlify-lambda build src"

With this in place, after saving the file, we can run npm start to begin netlify-lambda on port 9000.

The build command will be used when we deploy to Netlify later.

Once it is up and running, we can visit http://localhost:9000/.netlify/functions/server/test to check our function is working as expected.

The great thing about netlify-lambda is it will listen for changes to our code, and automatically recompile whenever we update something, so we can leave it running for the duration of this tutorial.

Start ngrok URL

Now we have a test route working on our local machine, let’s make it available online. To do this, we’ll be using ngrok, a npm package that provides a public URL for our function. If you don’t have ngrok installed already, first run npm install -g ngrok to globally install it on your machine. Then run ngrok http 9000 which will automatically direct traffic to our function running on port 9000.

After starting ngrok, you should see a forwarding URL in the terminal, which we can visit to confirm our server is available online. Copy this base URL to your browser, and follow it with /.netlify/functions/server/test. You should see the same result as when we made our calls on localhost, which means we can now use this URL as an endpoint for Slack!

Each time you restart ngrok, it creates a new URL, so if you need to stop it at any point, you will need to update your URL endpoint in Slack.

Setting up Slack

Now that we have a function in place, it’s time to move to Slack to create the app and slash command. We will have to deploy this app to our workspace, as well as making a few updates to our code to connect our function. For a more in depth set of instructions on how to create a new slash command, you can follow the official Slack documentation. For a streamlined set of instructions, follow along below:

Create a new Slack app

First off, let’s create our new Slack app for these FAQs. Visit https://api.slack.com/apps and select Create New App to begin. Give your app a name (I used Fauna FAQ), and select a development workspace for the app.

Create a slash command

After creating the app, we need to add a slash command to it, so that we can interact with the app. Select slash commands from the menu after the app has been created, then create a new command. Fill in the following form with the name of your command (I used /faq) as well as providing the URL from ngrok. Don’t forget to add /.netlify/functions/server/ to the end!

Install app to workspace

Once you have created your slash command, click on basic information in the sidebar on the left to return to the app’s main page. From here, select the dropdown “Install app to your workspace” and click the button to install it.

Once you have allowed access, the app will be installed, and you’ll be able to start using the slash command in your workspace.

Update the function

With our new app in place, we’ll need to create a new endpoint for Slack to send the requests to. For this, we’ll use the root endpoint for simplicity. The endpoint will need to be able to take a post request with application/x-www-form-urlencoded data, then return a 200 status response with a message. To do this, let’s create a new post route at the root by adding the following code to server.js:

router.post("/", async (req, res) => {
 
});

Now that we have our endpoint, we can also extract and view the text that has been sent by slack by adding the following line before we set the status:

const text = req.body.text;
console.log(`Input text: ${text}`);

For now, we’ll just pass this text into the response and send it back instantly, to ensure the slack app and function are communicating.

res.status(200);
res.send(text);

Now, when you type /faq <somequestion> on a slack channel, you should get back the same message from the slack slash command.

Formatting the response

Rather than just sending back plaintext, we can make use of Slack’s Block Kit to use specialised UI elements to improve the look of our answers. If you want to create a more complex layout, Slack provides a Block Kit builder to visually design your layout.

For now, we’re going to keep things simple, and just provide a response where each answer is separated by a divider. Add the following function to your server.js file after the post route:

const format = (answers) => {
 if (answers.length == 0) {
   answers = ["No answers found"];
 }
 
 let formatted = {
   blocks: [],
 };
 
 for (answer of answers) {
   formatted["blocks"].push({
     type: "divider",
   });
   formatted["blocks"].push({
     type: "section",
     text: {
       type: "mrkdwn",
       text: answer,
     },
   });
 }
 
 return formatted;
};

With this in place, we now need to pass our answers into this function, to format the answers before returning them to Slack. Update the following in the root post route:

let answers = text;
const formattedAnswers = format(answers);

Now when we enter the same command to the slash app, we should get back the same message, but this time in a formatted version!

Setting up Fauna

With our slack app in place, and a function to connect to it, we now need to start working on the database to store our answers. If you’ve never set up a database with FaunaDB before, there is some great documentation on how to quickly get started. A brief step-by-step overview for the database and collection is included below:

Create database

First, we’ll need to create a new database. After logging into the Fauna dashboard online, click New Database. Give your new database a name you’ll remember (I used “slack-faq”) and save the database.

Create collection

With this database in place, we now need a collection. Click the “New Collection” button that should appear on your dashboard, and give your collection a name (I used “faq”). The history days and TTL values can be left as their defaults, but you should ensure you don’t add a value to the TTL field, as we don’t want our documents to be removed automatically after a certain time.

Add question / answer documents

Now we have a database and collection in place, we can start adding some documents to it. Each document should follow the structure:

{
   question: "a question string",
   answer: "an answer string",
   qTokens: [
       "first token",
       "second token",
       "third token"
   ]
}

The qToken values should be key terms in the question, as we will use them for a tokenized search when we can’t match a question exactly. You can add as many qTokens as you like for each question. The more relevant the tokens are, the more accurate results will be. For example, if our question is “where are the bathrooms”, we should include the qTokens “bathroom”, “bathrooms”, “toilet”, “toilets” and any other terms you may think people will search for when trying to find information about a bathroom.

The questions I used to develop a proof of concept are as follows:

{
  question: "where is the lobby",
  answer: "On the third floor",
  qTokens: ["lobby", "reception"],
},
{
  question: "when is payday",
  answer: "On the first Monday of each month",
  qTokens: ["payday", "pay", "paid"],
},
{
  question: "when is lunch",
  answer: "Lunch break is *12 - 1pm*",
  qTokens: ["lunch", "break", "eat"],
},
{
  question: "where are the bathrooms",
  answer: "Next to the elevators on each floor",
  qTokens: ["toilet", "bathroom", "toilets", "bathrooms"],
},
{
  question: "when are my breaks",
  answer: "You can take a break whenever you want",
  qTokens: ["break", "breaks"],
}

Feel free to take this time to add as many documents as you like, and as many qTokens as you think each question needs, then we’ll move on to the next step.

Creating Indexes

With these questions in place, we will create two indexes to allow us to search the database. First, create an index called “answers_by_question”, selecting question as the term and answer as the value. This will allow us to search all answers by their associated question.

Then, create an index called “answers_by_qTokens”, selecting qTokens as the term and answer as the value. We will use this index to allow us to search through the qTokens of all items in the database.

Searching the database

To run a search in our database, we will do two things. First, we’ll run a search for an exact match to the question, so we can provide a single answer to the user. Second, if this search doesn’t find a result, we’ll do a search on the qTokens each answer has, returning any results that provide a match. We’ll use Fauna’s online shell to demonstrate and explain these queries, before using them in our function.

Exact Match

Before searching the tokens, we’ll test whether we can match the input question exactly, as this will allow for the best answer to what the user has asked. To search our questions, we will match against the “answers_by_question” index, then paginate our answers. Copy the following code into the online Fauna shell to see this in action:

q.Paginate(q.Match(q.Index("answers_by_question"), "where is the lobby"))

If you have a question matching the “where is the lobby” example above, you should see the expected answer of “On the third floor” as a result.

Searching the tokens

For cases where there is no exact match on the database, we will have to use our qTokens to find any relevant answers. For this, we will match against the “answers_by_qTokens” index we created and again paginate our answers. Copy the following into the online shell to see how this works:

q.Paginate(q.Match(q.Index("answers_by_qTokens"), "break"))

If you have any questions with the qToken “break” from the example questions, you should see all answers returned as a result.

Connect function to Fauna

We have our searches figured out, but currently we can only run them from the online shell. To use these in our function, there is some configuration required, as well as an update to our function’s code.

Function configuration

To connect to Fauna from our function, we will need to create a server key. From your database’s dashboard, select security in the left hand sidebar, and create a new key. Give your new key a name you will recognise, and ensure that the dropdown has Server selected, not Admin. Finally, once the key has been created, add the following code to server.js before the test route, replacing the <secretKey> value with the secret provided by Fauna.

const q = fauna.query;
const client = new fauna.Client({
 secret: "<secretKey>",
});

It would be preferred to store this key in an environment variable in Netlify, rather than directly in the code, but that is beyond the scope of this tutorial. If you would like to use environment variables, this Netlify post explains how to do so.

Update function code

To include our new search queries in the function, copy the following code into server.js after the post route:

const searchText = async (text) => {
 console.log("Beginning searchText");
 const answer = await client.query(
   q.Paginate(q.Match(q.Index("answers_by_question"), text))
 );
 console.log(`searchText response: ${answer.data}`);
 return answer.data;
};
 
const getTokenResponse = async (text) => {
 console.log("Beginning getTokenResponse");
 let answers = [];
 const questionTokens = text.split(/[ ]+/);
 console.log(`Tokens: ${questionTokens}`);
 for (token of questionTokens) {
   const tokenResponse = await client.query(
     q.Paginate(q.Match(q.Index("answers_by_qTokens"), text))
   );
   answers = [...answers, ...tokenResponse.data];
 }
 console.log(`Token answers: ${answers}`);
 return answers;
};

These functions replicate the same functionality as the queries we previously ran in the online Fauna shell, but now we can utilise them from our function.

Deploy to Netlify

Now the function is searching the database, the only thing left to do is put it on the cloud, rather than a local machine. To do this, we’ll be making use of a Netlify function deployed from a GitHub repository.

First things first, add a new repo on Github, and push your code to it. Once the code is there, go to Netlify and either sign up or log in using your Github profile. From the home page of Netlify, select “New site from git” to deploy a new site, using the repo you’ve just created in Github.

If you have never deployed a site in Netlify before, this post explains the process to deploy from git.

Ensure while you are creating the new site, that your build command is set to npm run build, to have Netlify build the function before deployment. The publish directory can be left blank, as we are only deploying a function, rather than any pages.

Netlify will now build and deploy your repo, generating a unique URL for the site deployment. We can use this base URL to access the test endpoint of our function from earlier, to ensure things are working.

The last thing to do is update the Slack endpoint to our new URL! Navigate to your app, then select ‘slash commands’ in the left sidebar. Click on the pencil icon to edit the slash command and paste in the new URL for the function. Finally, you can use your new slash command in any authorised Slack channels!

Conclusion

There you have it, an entirely serverless, functional slack slash command. We have used FaunaDB to store our answers and connected to it through a Netlify function. Also, by using Express, we have the flexibility to add further endpoints to the function for adding new questions, or anything else you can think up to further extend this project! Hopefully now, instead of waiting around for someone to answer your questions, you can just use /faq and get the answer instantly!


Matthew Williams is a software engineer from Melbourne, Australia who believes the future of technology is serverless. If you’re interested in more from him, check out his Medium articles, or his GitHub repos.


The post Create an FAQ Slack app with Netlify functions and FaunaDB appeared first on CSS-Tricks.

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

Agregator najlepszych postów o designie, webdesignie, cssie i Internecie