<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Patrick J. McDermott on Medium]]></title>
        <description><![CDATA[Stories by Patrick J. McDermott on Medium]]></description>
        <link>https://medium.com/@pjmcdermott92?source=rss-e030cfd60225------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gBhcauf5_LEKCZUboZiRog.jpeg</url>
            <title>Stories by Patrick J. McDermott on Medium</title>
            <link>https://medium.com/@pjmcdermott92?source=rss-e030cfd60225------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:34:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pjmcdermott92/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating Layers in CSS]]></title>
            <link>https://pjmcdermott92.medium.com/creating-layers-in-css-d619581595c7?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/d619581595c7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 18:35:16 GMT</pubDate>
            <atom:updated>2022-04-25T18:35:16.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*GJ5pniMupCFB4MlU-7UuLA.png" /></figure><p>Layers have been a part of CSS since its inception. By default, there are three layers that determine how CSS styles are applied to a web page. Having separate layers makes overwriting code from a previous layer super easy, and each layer has its own hierarchy that ignores specificity. The three default CSS layers are the <em>Browser </em>layer<em> </em>(otherwise known as the<em> user agent</em> layer<em>)</em>, the <em>User Styles </em>layer, and the <em>Author Styles</em> layer.</p><p>The <em>Browser</em> layer of styles is the layer that defines the default styles that are applied to elements. The Browser layer is the reason why buttons, form input fields, and other common look different across different browsers. The browser layer gives each browser a unique look and feel.</p><p>The <em>User Styles</em> layer consists of custom styles that a user can inject into their browser to overwrite browser layer styles. This layer is not too common nowadays as most browsers do not support this option anymore, but there are certain settings and preferences (depending on the browser) that can be adjusted that will inject custom styles into the user layer and overwrite browser default styles.</p><p>The most common CSS layer is the <em>Author layer</em>. The author layer is where every piece of CSS code that a developer writes will live. If you have built any front-end web pages using CSS, then you have worked with the author layer.</p><p>The three CSS layers are ordered as listed above (Browser layer, User layer, and Author layer). This goes along with CSS’s <em>cascading </em>properties, as every style in a later CSS layer will override any style from a previous layer, regardless of specificity. This means that no matter how specific an element selector is in the Browser layer, even a generic selector for that element in the Author layer will override the browser styles.</p><p>It is very important to understand how CSS layering works and how styles in later layers override styles in previous layers, in order to take advantage of one of the newer features that has been introduced into CSS: a new layers API that allows you to define your own layers within the Author layer.</p><p><strong>How Do You Create Your Own Layers?</strong></p><p>That is a great question!</p><p>Creating our own layers in CSS is actually quite simple to do. We simply need to use the <em>@layer </em>keyword to create a custom layer and give it a name. The name can be anything that we want it to be. If you are familiar with the @media query and @animation API in CSS, then the syntax might look very much similar.</p><p>Let’s go ahead and walk through an example of how to create custom layers in our CSS. The code below will create two new layers: one layer called <em>one</em> and another layer called <em>two</em>. Both layers are completely separate from one another. You will notice that — much like in a media query — we write our CSS styles within curly braces {} for each layer:</p><pre>@layer one {<br>    input#myInput.very-specific-input {<br>       border: 1px solid red;<br>       color: red;</pre><pre>    }</pre><pre>}</pre><pre>@layer two {<br>   input {<br>     border: 1px solid green;<br>     background-color: grey;</pre><pre>   }</pre><pre>}</pre><p>Because each layer that we created above is separate from the previous layer, we can easily override any styles from layer one inside of layer two, no matter how specific the selector is. In the example above, even though the input element is selected by the ID of <em>myInput</em> and the class name of <em>very-specific-input</em>, any styles applied to this input will be overrode by the generic <em>input </em>selector in layer two.</p><p>Here is a visual representation of the hierarchy of the styles being applied to our webpage:</p><pre>1. Browser (User Agent) styles<br>2. User defined styles<br>3. Author Styles<br>   1. one<br>   2. two</pre><p>By creating new layers using the CSS layers API, it makes organizing out code and working with specificity so much easier.</p><p>Defining custom layers in CSS is just the very basics of how powerful this new CSS tool is for front-end developers. There is a lot of functionality that we can achieve by using custom layers in our CSS. Here some examples of the different things that we can do with custom CSS layers:</p><p><strong>Define Layer Order</strong></p><p>With CSS layers, you have the ability to define the order in which layers are applied to your CSS. All that we need to do to define the order of our layers is to use the <em>@layer</em> keyword, and then list each layer in order, in a comma-separated list. CSS will apply the layers in order, from left to right, with the last one on the right being the most specific layer.</p><pre>@layer framework, base, utilities, components</pre><p>Once layer order is defined, you can simply use the <em>@layer</em> keyword, followed by the layer name to add styles to each layer, and the order of the layers will not change since they are already defined.</p><p><strong>Import Layers</strong></p><p>When you are working with frameworks in vanilla CSS, you will often import them using the @import keyword, followed by the URL of the framework, like so:</p><pre>@import url(https://medium.com/&#39;./lib/bootstap.css&#39;);</pre><p>Let’s say that we want to add the framework to a specific layer in our stylesheet, though. This can easily be done by adding the <em>layer(layer-name)</em> to the end of the @import statement, like so:</p><pre>@import url(https://medium.com/&#39;./lib/bootstap.css&#39;) layer(framework);</pre><p>This will import the bootstrap.css styles and place them all in the <em>framework </em>layer of your stylesheet.</p><p>These are just a couple of examples of what can be done using the <em>@layer</em> API in CSS. There is a lot more that can be done, such as nesting layers and using anonymous layers, but these tools will likely be less common, as they are not as useful.</p><p>When using layers in CSS, there are a few important things to consider, in order to fully understand and utilize layers:</p><p>First, keep in mind that non-layered styles are considered more specific. If you have styles declared outside of an <em>@layer</em>, these styles will override any styles in your layers. Just think of unlayered code as code that is in a layer below all the other layers, and that it will override any declared styles in your other layers.</p><p>The next important thing to consider is the all too infamous <em>!important </em>flag that some developers love to use. The <em>!important </em>flag makes specificity and overriding previous styles difficult overall and it is no different with layers. Any style with the <em>!important</em> flag will override that style in any layer, no matter what order the layer is in.</p><p>The final consideration when it comes to using layers in CSS is browser support. As with any cool new feature of CSS, it is important to know which browsers support the feature, and if it is worth using that feature if it is not widely supported yet. The good news is that the CSS layers API is well supported by over 60 percent of modern browsers, and is well on its way to being fully supported across all browsers. In fact, once users update their browsers to the latest version, the CSS layers API <em>should</em> be supported.</p><p>In conclusion, I am super excited that CSS layers will be a feature in all browsers in a short period of time. Using CSS layers is going to really change how we organize our CSS code and help address a lot of frustrations and confusion surrounding specificity. If you have not yet, I would recommend experimenting with CSS layers and learning more about them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d619581595c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Hash Passwords Using Bcrypt]]></title>
            <link>https://javascript.plainenglish.io/securely-storing-passwords-using-bcrypt-30efea785728?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/30efea785728</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[bcryptjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 18:29:03 GMT</pubDate>
            <atom:updated>2022-02-23T04:58:44.707Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial on hashing passwords using bcrypt.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZbEO2x5hllXeqXLMC6brQ.png" /></figure><p>User authentication is perhaps the most crucial part of just about every website and web application on the internet. It is also a very tricky and difficult part of application development for a lot of developers — especially those that are just starting their careers.</p><p>One of the main reasons that it is so tricky is that passwords need to be handled and stored properly. In this article, I am going to discuss a relatively easy way to encrypt passwords using a cryptographic hashing library called Bcrypt.</p><p>This article will be part one of a multi-part series that discusses user authentication. In the next article, we will discuss how to generate an access token that will allow a user to authenticate without having to log in with a username and password on each request. Be sure to look for that article after this one.</p><h4><strong>What is Authentication?</strong></h4><p>In web development, authentication is the process of verifying the identity of a web user. Typically, users will log in to a website or web application using their username or their email address and a password. This information is submitted to the backend server, and if the information that the user provides matches the information stored in the database, then the user is authenticated and allowed to access the content that they were trying to access.</p><p>It is important to know that authentication is different from authorization. Authorization is the process that happens right after authentication that determines what resources a user has access to — such as specific files or pages on a website or data from a database. This article will not focus on authorization, and the examples that are presented will simply be focused on authentication.</p><p>When it comes to authentication, there are three types of information that is relied on to verify a user’s identity:</p><ul><li><em>What you know </em>— This is the more traditional form of authentication for websites and applications, and typically consists of a username and a password combination that must be supplied correctly in order to authenticate the identity of a user. If the user knows the correct username and password combination, they are authenticated and granted access. This is the form of authentication that this post will be focused on.</li><li><em>What you possess </em>— This could be in the form of a smartphone and/or mobile application, access card, security token, or digital ID card. This type of authentication is a little bit more secure — especially when it is combined with <em>what you know</em> information (for instance, in two-factor authentication when a user must supply their username and password, as well as a provide a one-time pin or grant access via an application on their smartphone).</li><li><em>What you are </em>— This is typically the most secure type of authentication, as it relies on biometric data, such as fingerprints, retinal scans, or facial recognition. Because the user must be physically present in order to authenticate their biometric information, this is the most secure form of authentication.</li></ul><p>Now that we have a better idea of what authentication is and the different types of authentication information that are used in applications, we can look at how to implement a simple authentication system in a NodeJS application. As mentioned, this article will focus on <em>what you know </em>information — in this case, a username and a password.</p><h4><strong>Hashing Passwords</strong></h4><p>When a user registers for an account on a website or application, their information is stored in a database on a server, so that the user can come back and login in the future and use this information to gain access to protected and secured content on the website or application. Because the information is stored in a database, we want to make sure that it is secured from the possibility of a hacker gaining access to the database.</p><p>We do not want to store users’ passwords in their clear text string format, as this is not very secure. If somebody is to gain access to the database maliciously, the user’s password will be compromised. Furthermore, because so many people use the same password or some variation of the same password across many different services and applications, if a password falls into the hands of a hacker, it could give the hacker access to anything that that user uses that password for across the internet.</p><p>When building our authentication system, we want to ensure that the user’s password is encrypted before it is stored in the database, and we do not want to store the plain text version of the user’s password anywhere on our server or in our database so that it is much harder for a malicious person to get ahold of the user’s password.</p><p>The best way to ensure that a user’s password is securely stored in our database is to convert it into a string that cannot be converted back to the original password. This is a mechanism known as <em>hashing</em>.</p><p><strong>What is Hashing?</strong></p><p>According to the dictionary, hashing means to take something and chop it into little pieces and jumble it up to look like a confusing mess. In computer terms, hashing data essentially means chopping it up into little pieces, jumbling it up, and putting it in random order so that it does not resemble the original data.</p><p>A hash function is a mathematical cryptographic algorithm that takes data of any size and converts it to a fixed-sized bit string. The most common cryptographic algorithms for hashing user passwords include the Message Digest (MDx) algorithms, such as MD5, and the Secure Hash Algorithms (SHA), which includes the widely used SHA-256 algorithm — though SHA algorithms are no longer considered to be as secure.</p><p>The key benefit to hashing a password is that hashing functions make it easy to compute a hash based on a text string, but it is nearly impossible to reverse the hash string or re-generate the original password string. This means that hashing functions tend to be a one-way encryption and cannot be “cracked” or un-encrypted. Furthermore, hash functions also make it nearly impossible to create an initial input value that will match the outputted hash string. This makes hashing functions a very practical and very secure means of safely storing passwords in our database. Once the string is hashed, the original password is completely forgotten about on the server and is never stored anywhere in the user database.</p><h4><strong>Small Changes Have Big Impacts</strong></h4><p>Another reason why hashing functions are a secure and practical way of storing passwords is that the output hash string is nearly unpredictable. Let’s look at an example:</p><p>Let’s say a user chooses <em>password123</em> as the password for their account. The MD5-generated hash string for this would look something like this: <em>482c811da5d5b4bc6d497ffa98491e38</em>. Another user chooses <em>password124</em> as their password. If run through the same hash function, this string would look like this: <em>e28a09fe9d8ded87ea3a909ffc35cc45.</em></p><p>As you can see, both hashed password strings are very different, even though the clear string passwords are only different by one character. A secure hashing function takes this a step further by combining the user’s plain-text password string with a unique <em>salt</em> string and then running the password through the cryptographic algorithm several times to generate a unique hash. This means that even if 10 users have the same exact password, all 10 hashes will look very different from one another, simply because each hash string has a unique salt string. This makes it even harder for a hacker to crack, as simply cracking one password will not give them access to multiple users’ information, even if the users have the same password.</p><p>When storing the user’s hash in the database, we store the hash and the salt string together, so that when the user comes back to log in later, the password that they provide can be combined with the salt string and then run through the same deterministic hashing function used when the user-created their account to compare whether the hashed version of the entered password and the stored hash is the same.</p><h4><strong>What is bcrypt?</strong></h4><p>When it comes to hashing passwords, there are a lot of different options. You can write your own hashing functions that rely on cryptographic algorithms, or you can choose to use a third-party library to hash your password for you. In this case, we are going to use a third-party library called bcrypt. The bcrypt NPM library is a password-hashing library that has all the needed steps for generating salt, hashing passwords, and comparing passwords to ensure that a user is entering the correct credentials, all in one package. It is very commonly used, with 100,000 weekly downloads, <a href="https://www.npmjs.com/package/bcrypt">according to NPM</a>.</p><h4><strong>Let’s Get Coding!</strong></h4><p>To better explain and demonstrate the concepts and implementation of the bcrypt hashing library, let’s create a new Node/Express server and implement bcrypt into a practical use case.</p><p><em>All of the final code for this tutorial can be found on my Github at</em><a href="https://github.com/pjmcdermott92/bcrypt-tutorial-medium"><em> this link</em></a><em>.</em></p><p><em>Please note: </em>In order to follow along with this tutorial, you will need to have npm installed and running on your machine, and you will need to understand how to create a web server using NodeJS and Express. For simplification, we are not going to bother connecting to a database in this case and will instead store our user data as objects in a regular JavaScript array.</p><p><strong>Step 1: Initialize your Project</strong></p><p>Let’s initialize a new project using NPM. In your terminal, navigate to the directory that you want to use to build out this project. Type the following command into your terminal, and press enter:</p><pre>npm init -y</pre><p>This command will initialize a new npm project using all of the default options and create a <em>package.json</em> file for you.</p><p><strong>Step 2: Install Dependencies</strong></p><p>In order to quickly build out our server, we are going to need to install some dependency libraries in our project. The libraries we are going to need are <em>express </em>and <em>bcrypt</em>. We can install these libraries using the following command in our terminal:</p><pre>npm i --save express bcrypt</pre><p>These libraries will likely take a moment to install. Once these are done, we do have one more library to install that will make development easier. This one is not a requirement to get the project running, but I prefer to use it, since it watches for changes and automatically restarts our server for us, rather than us having to stop and restart after each change. We are going to install the <em>nodemon </em>package as a development dependency. We can do this with the following command:</p><pre>npm i --D nodemon</pre><p><strong>Step 3: Create our Scripts</strong></p><p>Once nodemon has finished installing, let’s open our project in our IDE editor. I prefer to use VSCode, but you can use any IDE that you want to. Once the project is open, let’s navigate to the package.json file. The contents of the file should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*WRTdSQIKYQ2wmxBUhSOmkA.png" /><figcaption>Initial package.json file</figcaption></figure><p>Under the section that says ‘scripts’, we are going to want to remove the test script, since we will not be using it, and create two new scripts — one for running our server in development mode and one for running our server in production. We will also change the main entry point of our script to be <em>server.js</em> rather than <em>index.js</em>. Make the needed edits, and make sure your <em>package.json </em>file now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*AkQvzc1P2n1LujZGrcVuuw.png" /><figcaption>Updated package.json file</figcaption></figure><p><strong>Step 4: Create our server.js file</strong></p><p>Next, we will create our <em>server.js </em>file and set up our basic express server. If you have worked with Node and Express before, this should look familiar to you. At the root of your project, create a new file called <em>server.js</em>. Open the file in your IDE and type the following to set up your initial server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*U2HRFCLmnstTdXiXECvMhw.png" /><figcaption>Basic server.js setup</figcaption></figure><p>This code allows us to set up our basic express server and tell our machine which port to run the server on. Now, if you go back to your terminal and type the following command, nodemon should start your server for you:</p><pre>npm run devStart</pre><p>In your terminal, you should now see that the server is running and that nodemon is watching for changes. You should also see the message <em>‘Server running on Port 3000…’ </em>being logged out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*61kFM36gd80V9e3vlLxrHA.png" /></figure><p>If you get any errors in your console, go back and make sure that your server.js file is set up correctly.</p><p><strong>Step 5: Creating a Users array and a register route</strong></p><p>Next, we are going to create a route that allows us to create a new user. Typically, we would want to store this information in a database, so that the data is persisted each time the user tries to log in. For the sake of this tutorial, however, we are just going to use a variable that will hold our users&#39; array. We also need to import the bcrypt library into our <em>server.js</em> file in order to use it. Update your <em>server.js</em> file to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*Em_OFNMOY7Uw9Kx7EsZHFQ.png" /><figcaption>Updated server.js file to include bcrypt and register route</figcaption></figure><p>To summarize what this code is doing, here’s a breakdown:</p><ul><li>We are bringing in our bcrypt library into the server file.</li><li>We have created an empty array called Users that will be used to store our new users’ credentials.</li><li>We have created a POST route that will allow us to register a user. We are grabbing the name, username, and password from the request body.</li><li>Inside of that route, after we create our new user, we are then pushing their information to the Users array, and sending a status back to the client of 201, which means that an entry was successfully created. We are also returning the new user data to the client in json format.</li></ul><p>If we simply run our server as is and try to pass in the user’s data, we will encounter an issue. In order to parse the name, username, and password from our request body, we need to tell express to use the built-in json parser. For good measure, we will also tell express to use the <em>urlencoded</em>() method, and set <em>extended</em> to <em>true</em>. This allows a client to submit form fields as part of the request body, in addition to json.</p><p>Add the following code into your <em>server.js</em> file, just below the Users array:</p><pre>app.use(express.json());<br>app.use(express.urlencoded({ extended: true });</pre><p>Your new server.js file should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ndd6PGWRGHRc1L4KXElbg.png" /></figure><p><strong>Step 6: Testing our Route</strong></p><p>For testing HTTP requests made to our new server, we will need a REST client of some sort. Since the endpoint that we are hitting is a POST request, we cannot simply use our browser. There are a few options to use, but by far the easiest is to use Postman. If you do not already have it, <a href="https://www.postman.com/downloads/">download Postman</a> <a href="https://www.postman.com/downloads/">HERE</a>, and then continue this tutorial.</p><p>To make a request in Postman, let’s create a new POST request and type in <em>http://localhost:3000/register</em> into the address bar. We will also need to navigate to the <em>Headers</em> tab and enter the <em>Content-Type: application/json</em> header:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*71VaeSEyYwkEFKX5vaZQUQ.png" /></figure><p>Next, we will need to navigate to the Body tab, select ‘raw’ for the data type, and add in our user’s information using json:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*oNiLEG6dV5htYQ2HVfr0gw.png" /></figure><p>Once we submit the information, we should see a Response in the bottom panel of our Postman app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRE0bBfyIR_AOWfn2WJXag.png" /><figcaption>The response that is sent back from our sever</figcaption></figure><p>The fact that we received a response from our request means that everything is working so far. However, you will notice that the password that was returned is the clear text string that we provided when we registered our user.</p><p>This is clearly not what we want, as this is not very secure, and makes it easy for anybody that has access to the database to figure out the user’s password.</p><p>Let’s fix this by implementing the <em>bcrypt </em>library into the route.</p><p><strong>Step 7: Hashing user’s password with bcrypt</strong></p><p>Bcrypt works both synchronously and asynchronously. However, since password hashing is a CPU-intensive task, it is usually better to use bcrypt asynchronously. To do this, we will need to add the async flag to the front of our route’s callback function and ensure that we await the response from our hash function before storing the user data. Here’s how our register route in our server.js file should now look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*qLrEoe_dVrcH1x5FPdXw1Q.png" /><figcaption>Updated ‘/register’ route in server.js</figcaption></figure><p>Now, if we run the register user function again, we should see that the password is no longer returned as the clear text password, but rather a random string of characters. We have successfully hashed the password and have stored the user’s data in the Users variable with this hash instead of the password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Thv5oBF01oM1Jja8lYPHZg.png" /><figcaption>We now see the password returned as a hash string</figcaption></figure><p><strong>Step 8: Verifying a hashed password when a user logs in</strong></p><p>In the last step, we were able to successfully hash the user’s password. In this step, we will demonstrate how to compare a plain text password with a stored password hash in order to authenticate a user and ensure that they have entered the correct information.</p><p>This route is a little bit more complex to write, as we first need to check that the username exists in our database (or — in this case — our Users array), then we need to compare the password that the user enters against the hash string that is stored in the array. Let’s write out the route function, then we will walk through exactly what is happening in the function:</p><p>Add this function to your <em>server.js </em>file, just below the POST function for registering a user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*ZYLuuE8iNCa5JJWPkEDrug.png" /><figcaption>Our new ‘/login’ route</figcaption></figure><p>Here is a breakdown of what is happening in this route:</p><ul><li>The client is sending a POST request with the user’s supplied username and password.</li><li>The Users.find() method is checking our Users array for the specified username. If the username does not exist in the array, a status 403: Forbidden is being returned, along with a message to the client that the credentials are not valid.</li><li>If the username does exist in the array, the compare() method from the bcrypt library is called. This method takes in the clear text password and the hashed password string from the Users array and bcrypt will hash the cleartext password using the salt string from the stored hash to ensure that the passwords match.</li><li>If the passwords do not match, a 403 error code and a message are returned to the client indicating that the credentials are not valid.</li><li>If the user provides the correct username and password combination, a status of 200 is returned to the user, along with the user’s information and a success message.</li></ul><p><em>Note that we returned the same error message to the user whether they entered an invalid username or an invalid password. We did not indicate which of the values was incorrect. This is another way of keeping users’ information safe and secure in the authentication process on your applications. If a malicious user is trying to crack a user’s information with a rainbow table or some other means of brute force, we are not giving them any hints as to whether they have any of the correct information.</em></p><p><strong>Let’s test it out!</strong></p><p>Before we can send the request to the newly created Login route, we first have to reregister the user. This is because we are not using a database, and instead are creating a temporary variable in memory for our Users array. In a production application, we will want to use a database of some sort to persist user data, but for this example, this is just a simple solution.</p><p>Go back to Postman and send your registered user request again. Make sure that a status code of 201 is returned, along with the user’s data.</p><p>Now that we have a user in our array, let’s create a new request in Postman. This time, we will create a POST request to <a href="http://localhost:3000/login,">http://localhost:3000/login,</a> and we only need to provide the username and the password in our request body. Make sure that you are on the ‘raw’ tab, and that you select JSON from the drop-down menu for the content type.</p><p>Send the request, and you should see a response code of 200, along with a success message and the users’ information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iXPZFrgSrb35SiXY8dLUg.png" /><figcaption>We have successfully authenticated a user!</figcaption></figure><p>Now, try sending the request again with a different password and a different username. You should see the following response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*vOawt3Ef7R7c4rMnUi0zrw.png" /><figcaption>Incorrect passwords and invalid usernames return the same error.</figcaption></figure><p>Using the bcrypt library, it really is quite simple to hash user passwords and safely store them in a database.</p><h4><strong>Conclusion</strong></h4><p>In this article, we discussed what password hashing is and why it is important. We also discussed how to use the bcrypt npm package to hash users’ data before storing it in the user database on our server. The finalized code for this tutorial can be found on my Github <a href="https://github.com/pjmcdermott92/bcrypt-tutorial-medium">HERE</a>.</p><p>Be sure to subscribe so that you do not miss any posts! In the next post, we are going to look at another npm package called jsonwebtoken. Jsonwebtoken is a library that allows us to issue a signed and verified access token to a client that has been authenticated on our server. This token allows the user to access resources on the server without needing to supply a username and password for every single request. Be sure to check that!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our</em><strong><em> </em></strong><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30efea785728" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/securely-storing-passwords-using-bcrypt-30efea785728">How to Hash Passwords Using Bcrypt</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom Hooks in React]]></title>
            <link>https://pjmcdermott92.medium.com/building-custom-hooks-in-react-c3eb9c34ce38?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3eb9c34ce38</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Sat, 29 Jan 2022 04:06:32 GMT</pubDate>
            <atom:updated>2022-01-29T04:06:32.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIkoqnO8aWUDZ1mNloLvpw.png" /></figure><p>The power of using React hooks makes building out scalable applications so much easier. Thanks to the introduction of hooks in React 16.8, writing React components is as simple as writing a JavaScript function — literally. In React years past, in order to have access to state or a component’s lifecycle methods (such as componentDidMount() or componentWillUnmount()), you pretty much had to write out class components. Now, with the new React hooks — such as useState() and useEffect() — class components are, for the most part, no longer needed. Of course, you can still write your components as classes, since React — at least for the foreseeable future — has no plans to remove classes from react.</p><p><strong>What <em>is</em> a Hook?</strong></p><p>Simply put, a hook is a function that allows us to “hook” into React features, such as lifecycle methods and state, from our functional components. React actually has seven pre-defined hooks that we can use in our applications: <em>useState(), useEffect(), useContext(), useRef(), useReducer(), useCallback(), and useMemo(</em>). I’m not going to get into the specifics of what each of these hooks does and how to use them, as that is beyond the focus of this article. If you would like to learn about these hooks, you can do so on the <a href="https://reactjs.org/docs/hooks-intro.html">React documentation</a> page.</p><p>In my experience, the most commonly used hooks are useState(), useEffect(), useContext(), and useReducer(). I use these four hooks all the time throughout my React applications, as they allow me to set up global access to my application state, trigger different logical operations whenever a component loads or global state changes, and manage complex pieces of state that would otherwise require a lot more code to accomplish.</p><p><strong>How about Custom Hooks?</strong></p><p>Let’s talk about custom hooks. Custom hooks are reusable functions that you write that allow you to reuse component logic across several components. You can implement custom hooks simply by extracting the piece of logic that you need to reuse into its own function (and file), and import it into each component that you wish to use it in. A key thing to remember is that React hooks always start with the verb <em>‘use’</em> — for instance, <em>useFetch()</em>. When you name your hook function with the <em>use</em> keyword, React knows that this is a hook.</p><p>Custom hooks can be very useful in React for many different situations. For instance, in a financial portal app that I am currently building, I am using several custom hooks (combined with other React hooks — such as useState(), useContext(), and useReducer()) to add in custom, reusable features, such as a Toaster Alert function that allows me to invoke a standardized alert message to the user from any component in the application, without redefining the Alert logic. The custom hook for this service is called <em>useAlerts()</em>, and it gives me access to the <em>setAlerts()</em> function that I use to push an alert to the application’s global state.</p><p>I also have a custom hook set up, along with a context provider, that allows me to call up a reusable modal anywhere in the application, simply by importing my custom <em>useModal()</em> hook. These custom hooks, combined with React’s useContext() and useReducer() hooks, allow me to build a scalable application, and keep my code as DRY as possible.</p><p><strong>How do I create a custom hook?</strong></p><p>Creating custom hooks in React is relatively simple. Let’s take a look at an example of a component that is fetching placeholder data from the JSON placeholder API to populate a to-do list application.</p><p>Our initial A<em>pp.jsx </em>component might be written like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*gXQHtjWbXBxwKBlob65Muw.png" /><figcaption>App.js</figcaption></figure><p>This works out great for a small application, such as a single to-do page. But what if we need to use this same fetch logic inside of another component? We do not want to have to duplicate the same code again in the other component to use this function. This is where React custom hooks will come in handy. We can extract all of the fetch logic from this component into its own file called <em>useFetch.js</em>, where we will also export a default function named <em>useFetch():</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*leUUFeEibztHeqQux7q-zA.png" /><figcaption>useFetch.js</figcaption></figure><p>Now, we can simply import our useFetch() function into our app.jsx component (and any other component that needs access to this function) like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*lJkqzSyEekdarTVZyklwnQ.png" /><figcaption>Refactored App.jsx component, importing useFetch hook.</figcaption></figure><p>Let’s review what we have done in this custom hook:</p><ol><li>We have extracted the fetch logic from our app.jsx component and placed it inside of its own file called <em>useFetch.js</em>. The logic is contained within a function called <em>useFetch().</em> We are then returning the data that is fetched from this API call from our hook, as well as returning a boolean error value.</li><li>In the app.js component, we are importing our useFetch() hook, and utilizing it just like any other React hook. We have successfully created a reusable hook that we can import into any function across our React application, and use — without having to duplicate the fetch data logic.</li></ol><p><strong>One step further</strong></p><p>We have created a custom React hook that allows us to fetch data from the JSON placeholder API from any component, without rewriting the logic. This helps to make for a scalable application — but, what if we need to fetch data from a different URL inside of one of our components? We could write another fetch function for this — or, we could make our useFetch() hook even more reusable.</p><p>Let’s remove the hard-coded API url from the custom hook, and instead pass a url parameter into the useFetch() function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*BShd95dfI2GXhx2M2q-8Jg.png" /><figcaption>Refactored useFetch.js function</figcaption></figure><p>Now, inside of our App.jsx component, we can simply pass in the URL to our JSON Placeholder api.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*CHEKcGIjO-s_TzioVPdg8g.png" /><figcaption>Refactored App.jsx component</figcaption></figure><p>Everything works exactly the same as before, except now we have an even more reusable hook that can be used to fetch data from any URL inside of any component.</p><p>This is the power of React custom hooks. The example above is a very simple example of how to create a custom hook in React. Hooks can become even more complex than the one above, and you can even use other React hooks and custom hooks within your custom hooks to really make your application scalable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3eb9c34ce38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top Five Small Business Website Must-Haves]]></title>
            <link>https://pjmcdermott92.medium.com/top-five-small-business-website-must-haves-4c5a612f0acf?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c5a612f0acf</guid>
            <category><![CDATA[small-business]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[landing-page-design]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Sun, 23 May 2021 04:13:48 GMT</pubDate>
            <atom:updated>2021-05-23T04:13:48.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*YwzZ5q6-vxEmr9CJZJpDug.png" /></figure><p>In today’s world, if a business does not have a website, they are already behind the curve against their competition. Statistics have shown that better than 85 percent of consumers are searching for and comparing local businesses online. This means that a business without a website is missing out on a huge chunk of potential sales — just because they do not have a website!</p><p>With this statistic in mind, it is crucial that your business has a website. However, just throwing up any old website with some graphics, links, and text that describes your business is not enough, either. Having a terrible or ineffectively designed website can be just as bad (if not worse) than not having a website at all. Market research has determined that 45 percent of visitors stop engaging with a website if the imagery, colors, and layout are not appealing, or if the site is difficult to navigate or has no real “flow”.</p><p>Because of the large number of internet users that browse the web from their mobile phones, a website also needs to be responsive to virtually any screen size — from a hand-held mobile phone all the way up to a 4K high-definition resolution. If your website is not responsive, you are losing credibility with over half of your visitors, who may be leaving your site for a competitor’s site that is mobile-friendly — which potentially costs you sales. The same research and market studies have proven that roughly 50 percent of mobile visitors believe that if a website is not accessible AND mobile responsive, the business simply <em>does not care</em>, and they may decide to look elsewhere before opening their wallets. In fact, a lot of consumers judge the reputation and trustworthiness of a business by their online presence alone.</p><p>Your online presence is just as important as your physical business presence — especially in a post — COVID-19 world. In a typical year, close to 25 percent of all disposable income world-wide is spent online. Thanks to COVID-19, that number has close to doubled — meaning that more than half of consumers visited businesses via their websites and made purchases online.</p><p>When you consider the information above, you may be wondering exactly what you need to do to make your business’s online presence shine and help you stand above the competition. Aside from being accessible and mobile-responsive, what should your website include in order to show your visitors that you care, and that they can trust you enough to give you their hard-earned money in exchange for your service or product?</p><p>Here are five critical must-haves for any business website, in order to help you grow your online traffic and increase your sales:</p><p><strong>1.</strong> <strong>A strong header — </strong>When a visitor comes to your website, they are quickly going to make assumptions and judgements of your business based on your site. Most visitors will not scroll past a website’s “fold” — which is the top part of the website that is visible to the viewer without them having to scroll. On your website, you have five seconds to engage your visitors and tell them what they want to know.</p><p>Your header should effectively describe <em>what you do</em>- the main service or product that you offer. You also want to include a <em>value proposition</em> — essentially, “what is in it for me”, for your visitors. Show them the benefits that they will get should they decide to work with you or purchase your service or product.</p><p><strong>2.</strong> <strong>A powerful Call-to-Action </strong>— Along with telling visitors exactly what you offer and how they can benefit, you also want to tell them exactly what you want them to do on your site. Do you want them to purchase your product or service? Should they learn more about your business or service? Should they subscribe to your email list?</p><p>A powerful call-to-action (also known as a CTA) is essential, and it needs to be visible in the “top fold” section of your site. Typically, CTAs come in the form of a button that users click that directs them to the next step they should take in the process, or it can be a form that prompts users for their email address. The CTA will typically be located right below your site’s header and sub-heading.</p><p><strong>3.</strong> <strong>Social Proof — </strong>The visitors that do stick around on your site and decide to scroll past the top half of your home page are interested in your business or services and are looking for more information about your business and why they should trust you. Having social proof that you can be trusted as an expert in your field is important, in order to gain a rapport with these visitors.</p><p>Social proof comes in many forms. The most common type of social proof are testimonials and reviews from previous clients that you have worked with. When a visitor sees that you have worked with other, real-life clients and have helped others in their industry fulfill their needs, it gives visitors a sense of relief and reassurance that you are a legitimate business and that you can be trusted to solve the visitor’s problem or fulfil their need.</p><p>One thing to be mindful of, however, is that you do not want to “make up” client reviews and testimonies just for the sake of making yourself look established and credible. If your visitors do find out that this is the case, you will lose any credibility that you have built with them and they will take their business to someone else that they know they can trust. It is always good to include a picture with testimonials, as well as a company name and job title to put a face to the name and assure visitors that these are real people. If possible, try to get video reviews as well.</p><p>Other forms of social proof include any awards, special licensing, and accolades that you or your business has received and that you can share on your site. If possible, share information that visitors can use to verify the validity and truthiness of these awards and accomplishments. And, while it is good to have some awards and accomplishments listed, do not overdo it. Limit the number of awards to avoid “bragging” too much about your business. Also, having your social proof strategically placed throughout the other information of your site (such as adding a testimonial to your Contact page, or showing some of your accomplishments and recognition on your about page) will help to instill trust in your visitors as they continue to browse your site.</p><p><strong>4.</strong> <strong>A reason to take action — </strong>More than likely, your visitors are viewing their site because they want to know <em>why </em>they should choose to work with you. In reality, while social proof is great and it’s good to show that you know what you are talking about, potential clients do not care about your story or the story of your business as much as what is in it for them, should they decide to work with you. Your site should be focused on what they will gain or get from clicking on your call to action — and they should be reassured of this as they continue to follow your funnel to the final step.</p><p><strong>5.</strong> <strong>Overview of Your Business — </strong>Your website <em>is </em>the face of your business — at least online. Your visitors are coming to your site to learn about your company, what you do, and how you can help them. While you want the focus of the site to be on showing visitors why they should hire you, you also want to give them the information that they need to fully understand your business, your product or service, and even your story. This adds to the trust that you are building with your visitors, as it allows them to learn about your business’s standards and values, and it adds that personal connection to the visitor.</p><p>Including an about section that tells a little bit about your business, how long you have been in business, how and when you started, and a few things that you have done is a great way to show visitors that your business cares and that it has credibility. It also helps to include names and pictures of a few key members of your team, and to give a brief description of their role and their personal story. This adds the “human” factor into the business, and helps potential customers realize that your business is made up of real people who care and who want to serve needs, just like them.</p><p>All the items listed above are the most critical things to include on your business website. Together with a modern, sleek, and custom design that is tailored to your business and is responsive to mobile devices, your website can and will achieve higher rankings on search engines and will receive more organic traffic, which will also lead to higher conversions.</p><p>Making your website a major key in your marketing plan is one of the best decisions that you can make to help boost your sales. In fact, your website should be the forefront to your digital marketing plan, and should reflect the personality, theme, and values that you want your business to convey. Add in social media marketing that connects with visitors and draws them to your site, and you should see an increase in traffic and conversions, just by investing in a professional quality website.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c5a612f0acf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Story — Why Did I Get into Development]]></title>
            <link>https://pjmcdermott92.medium.com/my-story-why-did-i-get-into-development-5aeac25ed67d?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aeac25ed67d</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[chefs]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 04:17:57 GMT</pubDate>
            <atom:updated>2021-04-05T04:36:29.454Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>My Story — Why Did I Get into Development</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgM2SQ-zGGvy00JV3gwowg.png" /></figure><p>Since a young age I have been interested in technology and computers. I got my first computer — a fossil by today’s standards — at the age of 12, and I did what any 12-year-old with a shiny new computer would do: I took the machine apart! I wanted to know about the inner workings and what made the thing tick. As you can imagine, my father was super happy with this choice (sarcasm, much?)</p><p>As I grew up, I took an interest in the web and how it worked, and in high school I took courses in web design and coding. The courses covered the basics of HTML and CSS (no JavaScript and nothing back-end), and they taught the very basics of design. I enjoyed it, and in my free time I continued to read and practice development, and by my senior year I had built a few sites for family businesses, local businesses in my community, and different programs at my high school.</p><p>Even though I was fully engulfed in web development, I ended up taking a different career path after high school graduation. Shortly after I graduated, I fell into some legal trouble (I was 19 and dumb) and one of the conditions of the program that I was in to amend my legal issues required me to get a job fast. I had court fines and restitution payments, and there weren’t a lot of tech companies in my area looking to hire a 19-year-old with little experience, no college education, and legal problems.</p><p>Because of this, I ended up taking a dishwasher job at a restaurant. The restaurant job satisfied my diversion program and allowed me to pay off my legal fees, but dealing with court dates and working full-time pulled me away from web development and put my goals for college on hold. I emersed myself in work at the restaurant and moved up quickly from the dish pit to the prep table and shortly after the cook line.</p><p>As a youngster without any other work experience, I quite enjoyed working in a kitchen. The other cooks and staff at the restaurant became a big support system for me and the chef of the restaurant that I was working at saw my potential and became my mentor in the culinary field. I learned a lot in a little bit of time and by the end of the first year at that restaurant I became a lead line cook on the busy dinner shift, and part of my job was to mentor and train new staff members. It was fun, and I felt as if I was adding value to something that was larger than myself.</p><p>As I was working my way up in the kitchen my dad’s health started to deteriorate. He was diagnosed with lung cancer and we were told that he did not have a lot of time left. In order to get the best treatment for him, it was recommended that he move to Arizona where he could see specialists and be in a drier climate, so I quit my job and my girlfriend and I moved with the rest of my family to the Mohave dessert of Arizona. I was able to get hired on quickly in a casino restaurant, and I built my career in food up from there.</p><p>Being in the kitchen and working my way up did not offer too much time for studying coding, so I pushed off college and web development indefinitely to focus on building my culinary career. In five years, I moved from one casino to another and worked my way up to a managerial level as a chef, and I opened up two restaurants in that time. I moved to Tucson, Arizona a few years back when my wife decided to attend the University of Arizona, and I got hired on at the University of Arizona as a chef, and I helped to open the newest dining concept on campus inside of the honor’s college.</p><p>Overall, for most of the ten years that I spent in food I enjoyed what I did. The downfall to this career was that when events and celebrations were happing at home, I was working. Every weekend, every holiday, every special event I worked. I missed valuable family time. This became especially more demanding when I moved from being an hourly employee to being salaried. It really started to hit me hard three years ago when my long-term girlfriend and I got married and decided that we wanted to work towards starting a family. In the evenings when she was out of work and school, I was working. On the weekends when she had days off, I worked. I just was not sure when I would have the time to help my wife raise a family.</p><p>I started to feel burned out from working all the time, and I reached a point in my career where I felt like I had advanced as far as I was going to. I wasn’t interested in graduating to the executive level and spending even <em>more</em> time at work and away from my family life. Because of this, I also realized that I was at the top end of the pay scale for my current career path. The amount of money I earned simply did not justify the time commitment and stress levels that I endured.</p><p>The final tipping point for me was when my executive level boss told me that people in this line of work must be passionate about spending most of their time at work, and that their families must learn to be okay with this. An executive in another restaurant that I worked at stated that the people you work with are equivalent to your family, and if you call in sick or take a vacation, you are “letting your family down”.</p><p>I did not agree with this philosophy at all. I have never believed that any person should <em>live to work</em>. In my mind, it was the other way around: I worked to <em>live</em>. On top of this, I was no longer passionate about what I was doing, and I dreaded going to work.</p><p>As I started to realize that working in a kitchen for the rest of my career was not ultimately what I wanted to do, I decided to make time for coding and learning web development. I was very rusty, and technologies had evolved way beyond my knowledge over the ten years that I was focused on building my food career. Getting back into code really reminded me of my passion for tech and web development, and I knew without a doubt that I was ready to change careers. Seeing all the success stories and freedom that other web developers boasted about made me want to change careers even more.</p><p>I built up on my coding knowledge and began taking on freelance work around my full-time chef job. I signed up for courses online and started watching tutorials and building projects, and my skills continued to grow. I became so engulfed in my coding studies that my managers at work were starting to notice that I had a new passion, and they started lecturing me about where my priorities needed to be and questioning my commitment to my job and the “family” that I have at work.</p><p>Even though I was taking on freelance work here and there and I felt like I was on the right track, I was still struggling to figure out just what I needed to do to finally make the leap to a new career in development. I did not have any mentorship or guidance whatsoever, and I felt stuck in my current career, and I didn’t know how to make the transition. I didn’t feel financially secure enough to quit my job and focus on my web development, and the COVID pandemic did not make this any easier.</p><p>Late in 2020 I signed up for the Devslopes academy and started to get the mentorship that I very much needed, and now I am working on transitioning from career chef to career web developer, and by the end of the current year (the same time that my wife graduates university to become a school teacher) I will be a developer fulltime. The journey has not been easy, and the most difficult part has been trying to overcome the imposter syndrome and the lack of confidence that I will succeed in my new career path, but the mentorship that I have received the past six months has been instrumental in helping me build that confidence. The past three years as chef have had me feeling “stuck” and not very enthusiastic about my career and lifestyle, but with my sights set on becoming a paid developer, I have a whole new outlook on my career and life overall!</p><p>Becoming a developer is a lot of work, but it is definitely worth it!</p><p>What are some of your stories? What has brought you to wanting to learn to code? Feel free to share them in the comments! It is very inspiring and encouraging to read the stories of success from others!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aeac25ed67d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamically Importing Modules in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/javascript-dynamically-importing-modules-94e1b88c420?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/94e1b88c420</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 20:03:38 GMT</pubDate>
            <atom:updated>2021-03-20T21:51:40.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5F1uobf9H8m6T7Pr" /></figure><p>When it comes to developing effective sites, page load speed is crucial — especially for user that are visiting from mobile devices on their mobile carrier’s network speed. In 2021, Google ranks sites based on several factors — from Cumulative Layout Shifts to page load speeds and unused JavaScript that bloats the files and decreases loading time and performance. By working diligently to reduce the number of scripts and the amount of time it takes to load a page, a site will score higher on Google and other search engines, which in turn will help users find your site and increase the number of visitors you receive.</p><p>In modern JavaScript, JS files can be broken down into multiple, smaller files and components can be exported only when needed. This helps with page load times and makes you codebase easier to manage and comb through should you or another developer need to review or refactor it later. Here is an example of how a JavaScript module can be imported into JavaScript:</p><pre>import User, { userDetail } from &#39;./Users.js&#39;</pre><p>This code will import the modules called Users and userDetails from the JavaScript file called ‘users.js’. You can import these components into other modular JS files only as needed. This is called a static import, and the biggest issue with importing modules in this manner is that the browser will download this code immediately when it is included — which can lead to very slow page loads, thereby hurting SERP ratings and even causing impatient visitors to navigate as far away from your site as they can.</p><p>A better way to implement modular imports in your JavaScript is to use dynamic module imports. Much like static module imports, you can import certain modules only when they are needed — but dynamic module imports allow you to import the code only where it is absolutely necessary using conditional logic statements. This will lead to much faster page load speeds because the browser is not trying to download all the JavaScript right away. If they user does not need to use a module, it will not be loaded.</p><p>There are a few ways to use dynamic module imports in JavaScript. Let’s look at dynamically importing the same module from above:</p><pre>import(&#39;./Users.js&#39;).then(({ default: User, userDetail }) =&gt; {<br>    //This will be the code that depends on the module...<br>});</pre><p>This method is pretty similar to statically importing the module, but instead this import is a function that returns a promise. The promise has all the details of the module. You will also notice that the default export of the module must be restructured from the return value of the promise. This where the default: User comes in — which is mapping the default export of the module to the User variable. This import function can be simplified and cleaned up even more by using an asynchronous function. Here’s an example:</p><pre>const { default: User, userDetail } = await import(&#39;./Users.js&#39;);</pre><p>This method will work exactly the same the promise function does, but just looks a lot cleaner and is easier to work with.</p><p>Using dynamically imported modules is beneficial for several reasons. The top three reasons that I can think of are to improve initial page loading speed and to avoid unneeded browser polyfills. Let’s say we are building an ecommerce application that utilizes a shopping cart feature. The logic for the shopping cart is fairly complex, and therefor requires a lot of code in order to function. Traditionally, all of this code will be downloaded by the browser immediately, which can result in a very slow page load. Dynamically imported modules, however, can combat this issue by allowing us to only download the logic for the shopping cart when the user actually interacts with the cart.</p><p>Here is an example:</p><pre>addToCartBtn.addEventListener(&#39;click&#39;, async () =&gt; {<br>  const { showCart, checkout } = await import(&#39;./cart.js&#39;);<br>});</pre><p>The above code will import the logic modules needed to add the functionality to the shopping cart, only when the user clicks on and ‘Add To Cart’ button. By doing this, the code for the cart is not loaded until it is absolutely needed, which will speed up page load speeds for visitors who may never interact with the cart.</p><p>On a lot of applications, there might be a lot of polyfills in place that allow support for features and functions on older browsers. These polyfills can drastically slow down page load speeds for users who do not need them, which can most certainly impact the user experience for visitors on modern browsers. We can use dynamic modules to import the polyfills only if they are needed:</p><pre>if (isLegacyBrowser) import(&#39;./polyfills.js&#39;);</pre><p>This import has no return value, because when a module is imported, all of the code in the module is imported and they polyfills will set themselves up automatically when they are needed. With this, a function that can be implemented that returns a value of true if the user is on an older browser, and then the polyfills module will be imported.</p><p>Another developer pointed out that when working on global applications, there can be a lot of files and code related to internationalization that offer support and translation for many different languages. By loading all these language support modules on initial load, the browser will download all of them, which will most likely reduce the page load speed for users. What if we had a way in which we only imported the internationalization files if they were needed — and even then, only the ones that are needed for the user’s specific language? This is yet another use for dynamically imported modules:</p><pre>const userLang = window.navigator.userLanguage<br>|| window.navigator.language<br>const { localStrings } = awai import(`strings.${userLang}.js`);</pre><p>This code allows the browser to detect the user’s preferred language based on their browser settings and loads in only the modules needed to support that language.</p><p>As you can see, dynamically imported modules is very useful in JavaScript. It allows for faster initial page loads, prevents the browser from downloading unused code, and provides for a faster, better user experience all the way around. The examples in this article are only a few of the amazing things that dynamically imported modules can do, but I hope that it gives you some helpful advice on how to improve the performance and rankings for your site or application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94e1b88c420" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-dynamically-importing-modules-94e1b88c420">Dynamically Importing Modules in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make A Simple Password Toggle Form With JavaScript]]></title>
            <link>https://javascript.plainenglish.io/tutorial-make-a-simple-vanilla-js-show-password-toggle-d4fc13d9293?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4fc13d9293</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 05:20:13 GMT</pubDate>
            <atom:updated>2021-02-07T07:49:24.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNx8d5JxTTgulb7USqnxIg.png" /></figure><p>In front-end development, there are times when you are creating a login or a sign-up form and you want to give the user the option to show their password so that they can make sure that they typed everything correctly, rather than hiding it behind dots or asterisks. With Vanilla JavaScript, this is a remarkably simple design element to implement, and it can help add to the overall experience that your UI conveys.</p><p>Let’s take a look at how we would implement a password visibility toggler without the use of any libraries, using plain Vanilla JavaScript and HTML/CSS.</p><h4><strong>First, Let’s Handle the HTML &amp; CSS</strong></h4><p>Before we can get to the fun part of this project — the JavaScript — we must first create our HTML document and add the elements that we need to it. This is pretty straight forward, provided you know HTML and CSS. You can go ahead and create your own login form and style it how you desire, or — if you prefer to copy my login form — you can <a href="https://github.com/pjmcdermott92/javascript-password-toggler">download it from my GitHub account</a>.</p><p>After you have your HTML in place, your form should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*8r8gT2IUfy2KIETtCWM_Pw.png" /><figcaption>Unstyled, ugly Login Form</figcaption></figure><p>Once the HTML is done, we can go ahead and create a style.css file and link our HTML document to it, and then we can style our form. Here is what the CSS for my login form looks like (<a href="https://github.com/pjmcdermott92/javascript-password-toggler">get it from GitHub here</a>):</p><pre>*, *::before, *::after { box-sizing: border-box; }</pre><pre>body {<br>    margin: 0;<br>    padding: 0;<br>    display: flex;<br>    align-items: center;<br>    justify-content: center;<br>    min-height: 100vh;<br>    background-color: hsl(207, 100%, 40%);<br>    color: #666;<br>    font-family: Verdana, Geneva, Tahoma, sans-serif;<br>}</pre><pre>.container {<br>    width: 100%;<br>    max-width: 400px;<br>    min-height: 30vh;<br>    padding: 1rem 2rem;<br>    background-color: #FFF;<br>    border-radius: .3rem;<br>}</pre><pre>h2, p { text-align: center; }<br>h2 { font-size: 2.5rem; }</pre><pre>a {<br>    color: hsl(207, 100%, 50%);<br>    text-decoration: none;<br>}</pre><pre>a:hover { color: hsl(207, 100%, 30%); }</pre><pre>.form-control {<br>    width: 100%;<br>    margin: 1rem 0;<br>    position: relative;<br>}</pre><pre>.form-control &gt; label { display: block; }</pre><pre>.form-control &gt; input {<br>    display: block;<br>    width: 100%;<br>    margin: .5rem 0;<br>    padding: .5rem .3rem;<br>    background-color: #EFEFEF;<br>    border: 2px solid transparent;<br>    outline: none;<br>    font-family: inherit;<br>    font-size: inherit;<br>}</pre><pre>.form-control &gt; input:focus { border-color: #999; }</pre><pre>.form-control &gt; input[type=&quot;submit&quot;] {<br>    border: 2px solid transparent;<br>    background-color: hsl(207, 100%, 35%);<br>    color: #FFF;<br>    text-transform: uppercase;<br>    font-weight: bold;<br>    letter-spacing: .1rem;<br>    cursor: pointer;<br>}</pre><pre>.form-control &gt; input[type=&quot;submit&quot;]:hover,<br>.form-control &gt; input[type=&quot;submit&quot;]:focus {<br>    background-color: hsl(207, 100%, 40%);<br>}</pre><pre>.form-control &gt; input[type=&quot;submit&quot;]:focus {<br>    border-color: #999;<br>}</pre><p>My form now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQ2zFSTlYeWTNW31dDT_Ow.png" /><figcaption>Much better! Now it looks good! (ish)</figcaption></figure><p>It is a very simple and very straightforward login form without too many fancy elements and styles, because the main purpose of this tutorial is to demonstrate how to add the functionality of the login form.</p><h4><strong>Lets Add the Toggle Icon</strong></h4><p>There are a number of ways that you can choose to allow users to toggle their password’s visibility, including a checkbox that is labeled ‘Show Password’ that the user can check or uncheck, and an icon that can be clicked that will toggle the password’s visibility. For the purpose of this project, I chose to use an icon that can be clicked to toggle the visibility of the password.</p><p>In this case, I am using FontAwesome to display the icon via a Content Delivery Network, because this is a relatively simple solution that does not require me to host the icon files with my project. To get a FontAwesome CDN, head over to <a href="http://www.fontawesome.com/start">www.fontawesome.com/start</a> and login or signup for free to create a new webkit.</p><p>Then, simply copy and paste your FontAwesome Kit’s Code &lt;script&gt; tag in the &lt;head&gt; section of your HTML file, right below your stylesheet &lt;link&gt; tag. That’s it! You are ready to go! Next, simply search for what type of icon you are looking for, and FontAwesome will give several options — both free and premium, if you have a premium account — to choose from.</p><p>In my case, I searched for ‘eye’ and I chose these icons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*xey9CEiELMeLW7W34kRoMQ.png" /></figure><p>I needed two different icons — one with just the eye and one with a slash through it — to indicate whether password visibility is toggled on or toggled off. You can use the same icons that I chose, or you can choose your own icons. It is up to you.</p><p>In order to display and position our toggle button correctly on the right side, inside of our Password field, we need to wrap it in a &lt;span&gt; tag with a class name (in this case, I used ‘toggle-password’) and placed inside of my password field form-control div, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*Djym3eByzVM8RaNJ6TQ-HA.png" /></figure><p>Next, we need to go into our CSS and add a style for our toggle button element:</p><pre>.toggle-password {<br>    position: absolute;<br>    top: 40%;<br>    right: .5rem;<br>    cursor: pointer;<br>    user-select: none;<br>}</pre><p>By using position: absolute and setting the top and right positions of the toggle button, we are able to place it right where we want it, so that it looks like it is inside of the password field. However, if you just leave your code as it is now, you will notice that the icon will vanish from the page. This is because we also need to set our form-control elements to a position: relative, so that the icon positions itself relative to the form-control that it is placed inside of:</p><pre>.form-control {<br>    width: 100%;<br>    margin: 1rem 0;<br>    position: relative;<br>}</pre><p>You many need to tweak the top and right positioning of your icon a little bit until it looks just as you want it to. For me, the values that I specified seemed to place the icon just where I wanted it to be.</p><h4><strong>Hide the Toggle Icon — for now!</strong></h4><p>Now that the icon is positioned exactly how we want it, we can go ahead and hide it for now. This is optional, but I chose to hide my icon when the password field is blank, simply because I felt like it looked better this way. You don’t have to hide yours, but this is what I chose to do.</p><p>To hide the icon, in our CSS we need to grab the &lt;i&gt; element that is inside of the ‘toggle-password’ span. We can use the CSS child combinator sign &gt; to select the &lt;i&gt; tags that are nested directly inside of an element with the class name of “toggle-password’. All we need to do is set the display property of this element to none:</p><pre>.toggle-password &gt; i { display: none; }</pre><h4><strong>Time for some Fun! Let’s Move on to the JavaScript!</strong></h4><p>We are now done with the HTML and CSS portion of this project and are finally ready to add the functionality using JavaScript! To begin, let’s create a new JavaScript file in our project’s root directory and name it scripts.js. We can link the new file to our HTML document by placing the &lt;script&gt; tag in the &lt;head&gt; section of our document, right below the &lt;script&gt; tag for our FontAwesome CDN:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*uIOkJVi-8gfC-_ARSB_01w.png" /></figure><blockquote><strong>IMPORTANT:</strong> when placing our JavaScript files in the &lt;head&gt; section of our HTML document, it is essential to include the defer attribute. By telling the browser to defer the loading of the script tag, the browser will skip the loading of the JavaScript file until after the Document Object Model has loaded. This is to ensure that all of the elements that will be referenced in our JavaScript code will be loaded into the DOM, so that they can be found. If we did not defer the loading of our document, our JavaScript would not work and we would find an error in our browser’s console, because the elements did not exist when the script file was loaded.</blockquote><p>There are alternatives to including the defer attribute in your script tag. The first one is to simply add the &lt;script&gt; tag to your HTML document’s &lt;body&gt; section, below all other elements. This works because the browser renders the HTML file in a cascading manner, from top to bottom, so by the time your script tag is parsed and loaded the entire DOM will already be rendered.</p><p>You could also include the &lt;script&gt; tag in your &lt;head&gt; section with the defer attribute and wrap your JavaScript code in an event listener function that is called when the DOM CONTENT LOADED event occurs, like so:</p><pre>window.addEventListener(&#39;DOMContentLoaded&#39;, (event) =&gt; {<br>    // Your Code Here....<br>});</pre><p>This is an older way of ensuring that everything in your DOM is rendered before the script executes, and while it works just fine, it makes the code look messier since you have nested logic right off the bat.</p><p>For the purpose of this project, we are going to stick with the defer attribute and keep the &lt;script&gt; tag in our head section. This is my preferred way of organizing my files, as it helps me keep my script tags and my link tags all neatly organized in the &lt;head&gt; section of my HTML, and I don’t have to worry about extra tags in the &lt;body&gt; section of the page, and it can strictly handle the page structure.</p><p>Now that we have our JavaScript file set up, we can test to make sure that everything is linked up and functions as we expect it to. To test your script file, add the following line of code to your JavaScript file, save it, and reload the page in your browser:</p><pre>alert(&#39;THIS WILL POP UP IF EVERYTHING WORKS!!&#39;)</pre><p>You should see an alert box pop up that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*4ynrBsgnANQ-I0a1Hnhd4w.png" /></figure><p>If the alert box pops up, everything is working as it should and you are golden! If it does not, go back and check the &lt;script&gt; source to make sure that it is pointing to the right file and directory, and ensure that your scripts.js file is in the correct directory.</p><p>Once everything is linked up correctly, we need a way to select the elements that we want to add functionality to in our JavaScript. In our case, we need to have access to the password input field and our password toggle icon. There are several ways to select HTML element using JavaScript methods, but if you have read my article on <a href="https://pjmcdermott92.medium.com/why-i-use-custom-data-attributes-for-selecting-elements-in-javascript-58166fe074a8">using custom data attributes to select HTML elements</a>, you will realize that this is my preferred way of selecting DOM elements, so this is the method that we will use.</p><p>Let’s add a custom data attribute to each of the elements that we need to select:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*LvJ-k6SP3uq67h3i49nUhQ.png" /></figure><p>Now, in our JavaScript file, we can grab these elements from the DOM using the <em>querySelector()</em> method and store each of them in a variable for use in our JavaScript:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*tFKSI2X4mWIMjgp5_-XX8g.png" /></figure><p>Now, let’s make our project do something! First, let’s add an event listener to our password input field that ‘listens’ for an input into the field and calls on a function to display our toggle button:</p><pre>passInput.addEventListener(&#39;input&#39;, showToggleButton)</pre><p>Next, we can go ahead and create the <em>showToggleButton()</em> function and tell it what to do, using a conditional if…else statement:</p><pre>function showToggleButton() {<br>   if (passInput.value.length &gt; 0) toggleBtn.style.display = &#39;block&#39;<br>   else toggleBtn.style.display = &#39;&#39;<br>}</pre><p>This function looks at the length of the value of the password field, and if there is actually a value (greater than zero character), it sets the display style of the toggle button icon to ‘block’, which allows it to show up on the screen. Otherwise, it will remove the display style attribute, and the element will default back to<em> display: none</em>.</p><p>Let’s go ahead and add one more event listener to our password input field. This event listener will be called when the password input field is focused (or when a user selects it to type into it). This event listener will check if the password is visible and if the length of the password is less than 1. If it is, it will call the <em>togglePasswordVisible()</em> function again and hide the toggle icon, since the password field is empty:</p><pre>passInput.addEventListener(&#39;input&#39;, showToggleButton)<br>passInput.addEventListener(&#39;focus&#39;, () =&gt; {<br>  if (showPassword &amp;&amp; passInput.value.length &lt; 1) {<br>     togglePasswordVisible()<br>  }<br>})</pre><p>In order for this to work, we will need to declare the variable ‘passwordVisible’, since we made reference to it in the function. We can just place it at the top of the file (just below the input and toggle button selector variables) to make it globally accessible:</p><pre>let showPassword = false</pre><p>This variable uses the let keyword instead of const so that the value can be reassigned. This will play a role in showing and hiding the password and determining which icon to show. We also define a default value of ‘false’ to the variable because we do not want out password visible unless the user clicks on the toggle button to display it.</p><p><strong>Add an Event Listener to the Toggle Button</strong></p><p>Next, we need to add an event listener to the toggle button so that it will call a function and perform an operation when the user clicks on it. In our case, we first want to call a function called <em>togglePasswordVisible()</em>, and then we want to focus on the password input field:</p><pre>toggleBtn.addEventListener(&#39;click&#39;, () =&gt; {<br>    togglePasswordVisible()<br>    passInput.focus()<br>})</pre><p>Let’s create the <em>togglePasswordVisible()</em> function, which will switch between showing the password that the user typed or hiding it and showing the ‘dots’:</p><pre>function togglePasswordVisible() {<br>    showPassword = !showPassword<br>    if (showPassword) {<br>        toggleBtn.classList = &#39;fas fa-eye-slash&#39;<br>        passInput.setAttribute(&#39;type&#39;, &#39;text&#39;)<br>    } else {<br>        toggleBtn.classList = &#39;fas fa-eye&#39;<br>        passInput.setAttribute(&#39;type&#39;, &#39;password&#39;)<br>    }<br>}</pre><p>This function is pretty simple, and all that it is doing is taking the current Boolean value of the <em>showPassword</em> variable that we defined earlier and setting it to the opposite of its current value (if it is true, it will be set to false, and vice versa).</p><p>The function then looks to see what the new value of showPassword is and it sets the class attribute for the icon to either fa-eye-slash (indicating to hide the password) or to fa-eye (indicating to show the password). It also sets the type attribute for the text box to either text (if the password is visible) or password (if the password is hidden).</p><p>Let’s save our work and test out our project! When the page first loads, the password field should be empty, and the icon should be hidden. Once a value is typed into the password input, the icon should show up without a slash, and the password should be hidden by dots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgA4wQZ8UVvowHQonDlJhQ.png" /><figcaption>On first load, password field is blank and icon is hidden. Once user inputs a value, the icon is visibile.</figcaption></figure><p>If the eye icon is clicked, it should change to an icon with a slash through it and the password should be visible as text:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*Za5CokXUflXWjNcduifW8Q.png" /></figure><h4>Conclusion</h4><p>Did your toggler work? If so, awesome! Hopefully you enjoyed this tutorial and will be able to use this concept in a real-life project!</p><p>If you enjoyed this tutorial, I will be creating more just like it and in the very near future I will be relaunching my blog and portfolio website, where I am planning to feature many more tutorials. Information on the launch of this site will be released very soon! Feel free to subscribe to my feed so that you will be notified of this launch and so that you never miss a new article release!</p><p>Thank you for reading and Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4fc13d9293" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/tutorial-make-a-simple-vanilla-js-show-password-toggle-d4fc13d9293">Make A Simple Password Toggle Form With JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS clamp() Function for Responsive Fonts]]></title>
            <link>https://medium.com/swlh/css-clamp-function-for-responsive-fonts-1fe78fa20d7f?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe78fa20d7f</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[css3]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Fri, 05 Feb 2021 17:08:35 GMT</pubDate>
            <atom:updated>2021-02-05T17:08:35.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XFX2yK7KZJtrQO4UTG6vQ.png" /></figure><p>If you have spent any time developing responsive web sites, I am sure that you, too have realized that getting your font size to scale to the size of the viewport without looking too small on smaller viewports and too large on larger viewports is not always easy. I have struggled with this issue a lot in my experience as a developer, and in order to solve the issue I have found myself adding media queries with just single selectors that will adjust the font size of certain elements based on the viewport size.</p><p>As you can imagine, this approach requires extra code and time in order to achieve the results that I am going for. In recent weeks, upon researching the different functions that have been available in CSS3, I discovered the CSS <em>clamp()</em> function. This is a simple yet powerful function that can be applied to elements that will allow your font size to change based on the viewport but keep it from shrinking down too small or growing too large.</p><p><strong>What is the CSS <em>clamp()</em> Function?</strong></p><p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/clamp()">MDN Docs</a>, the CSS <em>clamp()</em> function is a mathematical CSS function that allows you to ‘clamp’ a value between a defined minimum and maximum range. The <em>clamp()</em> function takes in three parameter — the minimum, the preferred value (essentially the ‘base’ value), and a maximum value. Each value is separated by a comma. Here is an example of the syntax for the <em>clamp()</em> function:</p><pre>.my-text-element {<br>    font-size: clamp(1rem, 2vmin, 3rem);<br>}</pre><p>In the above example, we are setting our <em>font-size</em> to <strong>2vmin</strong>, but we are also specifying a minimum and a maximum for the font-size. By using the <em>clamp()</em> function to define our <em>font-size </em>for the specified element, it allows our font-size to scale with the size of the screen at a ratio of <strong>2vmin</strong>, but it will never allow the size of the font to go below a value of <strong>1rem</strong> or above a value of <strong>3rem</strong>.</p><p>This is the simplest and most effective method for creating mobile-responsive font sizes that I have come across. By using the <em>clamp()</em> function in my CSS, I have been able to reduce the number of lines of CSS that I have needed and I do not have to specify as many media query break points as I used to.</p><p>Perhaps the coolest thing about the <em>clamp()</em> function is that it is not just limited to font-sizes. According to the function’s documentation, the<em> clamp()</em> function can be used anywhere that you want to specify a <em>length, frequency, angle, time, percentage, number</em>, or <em>integer</em> value. This means that you can use the <em>clamp()</em> function to specify the width of elements based on minimum and maximum parameters.</p><p><strong>Achieving the Perfect Width</strong></p><p>Another cool use for the<em> clamp()</em> function is to set the perfect width of elements. For instance, the acceptable width of a paragraph on a single-column page is considered to be anything between 45 and 75 characters, varied by the actual size if the font being used. The <em>clamp() </em>function makes this type of sizing super simple, using the 0-width character advance unit (ch) with the <em>clamp()</em> function:</p><pre>p {<br>width: clamp(45ch, 50%, 75ch);<br>}</pre><p>The above code will tell the browser to set the width of the paragraph to 50%, unless 50% is smaller than 45 characters or larger than 75 characters — in which case either 45ch or 75ch will be selected as the width of the paragraph, respectively.</p><p>In conclusion, the CSS math function <em>clamp()</em> is relatively easy to understand, and is a very powerful tool to add to your CSS toolbox. This function makes it possibly to size elements in a way that before might have seemed impossible or was extremely difficult to achieve. The <em>clamp()</em> feature is also widely supported in most modern browsers as of late 2019, and it could be just the tool that you need to help you build fluid, responsive user interfaces.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe78fa20d7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/css-clamp-function-for-responsive-fonts-1fe78fa20d7f">CSS clamp() Function for Responsive Fonts</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Styling Chrome, Firefox, & Opera Mobile Theme Color with Meta Tag]]></title>
            <link>https://pjmcdermott92.medium.com/styling-chrome-firefox-opera-mobile-theme-color-with-meta-tag-e014fc5edd07?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/e014fc5edd07</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Wed, 27 Jan 2021 01:41:00 GMT</pubDate>
            <atom:updated>2021-01-27T01:41:00.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMJ5nwdBNQAZLsDVA1o90A.png" /></figure><p>In today’s internet world, having a website is not enough. With over 50 percent of web users browsing the internet via mobile devices — from mobile phones to tablets and even smart watches — it is important for your website to be responsive and mobile friendly. Sure, you have heard this many times before — it is sort of an obvious “rule of thumb” nowadays. More important than the site just looking good on mobile screens, however, is delivering a user experience to mobile users that is akin to the experience that they would get if they visited the site on a desktop or laptop.</p><p>Mobile visitors need to experience the level of care and detail that goes into a good responsive website. With mobile screens having very little real estate to display graphics, text, and animations compared to desktops and larger viewports, it is crucial that every detail on the site serves a purpose and adds to the user’s experience. High level animations, videos, and interactivity should also be kept to a minimum for mobile users, as this will slow down load times at mobile data speeds as well as eat up the user’s mobile bandwidth.</p><p>So, with all these limitations on what can be delivered to mobile users, how can a developer go above and beyond to show mobile users that they are valued just as much as desktop users? What extra elements can be added to the user experience that will have an impact on the appearance of the site without taking away from the load time, eating up the mobile user’s bandwidth, and compromising the experience that a desktop user would have?</p><p>First, it is important to make sure that every element of the site scales nicely to fit on mobile screens, and that as the size of the screen increases, the available real estate is utilized properly to balance out white space with content in a way that is visually appealing. Hiding small, less significant graphics and images on smaller screens and making them visible on larger screens where it makes sense to have them is one of the best ways to utilize the available viewport.</p><p>Another often overlooked element that can be added to mobile-friendly websites is the custom theme element meta tag. This single line of code can be added to the head section of the site’s pages and allows the developer to specify a custom color for the browser address and menu bar on mobile devices. The meta tag looks like this:</p><pre>&lt;meta name=”theme-color” content=”#EFEFEF”&gt;</pre><p>Adding this tag to your website’s theme will help ensure that your site stands out from other sites that do not utilize this simple yet powerful tip. This small line of code will give your website the feel of a mobile application, right in the user’s browser, which is a trend that continues to grow in the mobile web development world.</p><p>By customizing the color of the user’s browser with this single meta tag to match the overall color scheme of your website’s theme, your site will have a more app-like feel and it will add a level sophistication to the look and feel of the overall site theme. Your visitors will subconsciously feel the level of pride and professionalism that you have put into the user experience and overall design of the site. Plus, it will help your site stand out from ‘the crowd’.</p><p>There are a few important things to note about this meta tag, however.</p><p>First, if the user has their browser set up in dark or high-contrast mode, this tag will be ignored, and the color of the browser will not be affected. This is for accessibility and is perfectly fine. You should still include this tag in your site’s header section for users that do not use high-contrast and dark mode.</p><p>The second thing to note is that this tag is not compatible with all mobile browsers. The theme color works on Chrome and Safari (which make up a large portion of mobile devices that run on Android and Apple’s iOS). In recent years, it also works in Firefox as well. If, for some reason, a user is visiting the site from an unsupported browser, the tag will simple be ignored.</p><p>A final thing to note is that this tag only supports a single color (you cannot set gradients and multiple colors). It also only supports hexadecimal color values.</p><p>The bottom line is that you should start including this tag in the header section of any website that you build. Most mobile users will be visiting your site from a compatible browser, and only a handful will be using high contrast and dark themes, so the added benefit of changing the user’s browser color to match the overall theme of your website is worth it. In addition, this is a relatively small way to add an extra pop and wow-factor to the user experience, since this single line of code only takes about 43 bytes of data to load.</p><p>Even if your site’s primary color scheme is mostly white (for instance — a minimalistic or ‘material’ blog theme with a white background and black text, and no images or accent colors) it is still a good idea to include this tag and set the value to the hexadecimal value for white (#FFF or #FFFFFF). Again, this code takes very little data to load and adds virtually no time to the loading speed of the site.</p><p>For progressive web applications — a trend that is gaining traction and popularity quickly, especially for mobile sites — specifying the color that the browser should use for menu and tab colors is a must.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e014fc5edd07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Cleaner JavaScript with Guard Clauses]]></title>
            <link>https://pjmcdermott92.medium.com/writing-cleaner-javascript-with-guard-clauses-fe4bb8788425?source=rss-e030cfd60225------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe4bb8788425</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[guards-clauses]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Patrick J. McDermott]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 22:02:22 GMT</pubDate>
            <atom:updated>2021-01-27T01:55:00.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKhcXag3nxdrMVl6ujVkfg.png" /></figure><p>When I first started programming with JavaScript, my conditional logic statements were often comprised of massive amounts of nested if…else if…else statements. Initially, when writing these statements, they made sense because they walked through the logic step-by-step and the function executed properly based on the logic. Hoverer, weeks or months later when I needed to update or change the logic in my massive conditional blocks, I would have to parse through and understand the logic all over again. Even with the simplest functions, parsing through multiple levels of nested conditional logic was a difficult and time-consuming task. On top of that, I would have to spend a lot of time debugging and restructuring my code in order to keep everything working with the new changes I added.</p><p>At first, I thought that the frustration and time involved in working and reworking the conditional logic was unavoidable and just ‘part of the territory’, even if it was frustrating and seemed counter-productive. I was writing the logic exactly the way I worked through it in order to create the function.</p><p>Over time and with lots of practice and time spent of Google, I learned that there is an easier, cleaner, and more sensible way to write my conditional logic functions that achieve the same results but that look cleaner and are much easier to follow. I learned about the ‘magic’ that is guard clauses.</p><p><strong>What is a Guard Clause?</strong></p><p>A guard clause is a piece of conditional logic that is placed at the beginning of a function that will return out of the function early on if certain conditions are not met. Guard clauses are simple to implement in any function that involves conditional logic, and they make functions shorter and cleaner.</p><p>Let’s take a look at a very simple example of how guard clauses can help shorten and clean up conditional logical functions. Below is a function that determines if a player has already attacked a specific location:</p><pre>function checkForPlayerStrike(strike) {<br>  if (playerStrikes.includes(strike)) {<br>    error = true<br>    error.message = &#39;You already hit this location.&#39;<br>  }<br>}</pre><p>This function is relatively straightforward — if the playerStrikes array contains the current strike, then the player has already hit that location and an error message is displayed.</p><p>How would we rewrite this function using a guard clause to clean it up a little bit? Here’s an example:</p><pre>function checkForPlayerStrike(strike) {<br>  if (!playerStrikes.includes(strike)) return<br>  error = true<br>  error.message = &#39;You already hit this location.&#39;<br>}</pre><p>The above function does the same thing that the first one does. The logic is the same, but the function is only run if the <em>playerStrike</em> array contains the specified strike area. You will notice that the guard clause is the opposite of the conditional logic statement in the first function, and it will simply return out of the function without running it if the condition is not met. The actual logic is also no longer nested inside of a conditional statement since it will only be executed if the guard clause is false.</p><p>Adding a guard clause to a function as simple as this may not seem to make a lot of sense, as the difference is not significant. To further demonstrate the usefulness of guard clauses, let’s take a look at a more complex function.</p><p>The below function might be an example of a function that might be used to determine the deductible that a patient pays out of pocket for a certain medical procedure:</p><pre>function patientDeductuble(procedure) {<br>  if(procedure.covered) {<br>    if(procedure.inpatient) {<br>      return 2000<br>    } else if (procedure.outpatient) {<br>      return 1000<br>    } else {<br>      return 1500<br>    }<br>  } else {<br>    return &#39;Procedure is not covered by insurance!&#39;<br>  }<br>}</pre><p>Looking at this function, it might be a little bit difficult to decipher exactly what is going on at first glance. You have to dig into the function line by line to determine exactly what the logic is and what the function returns, based on the condition. We could clean this function up by using guard clauses and the result might look like this:</p><pre>function patientDeductible(procedure) {<br>  if (!procedure.covered) return &#39;Procedure is not covered by insurance!&#39;<br>  if (procedure.inpatient) return 2000<br>  if (procedure.outpatient) return 1000</pre><pre>  return 1500 // Procedure is Elective.<br>}</pre><p>The above function is a lot cleaner and easier to follow with a quick glance. It is also much shorter and much cleaner to look at. The logic of the function is the same as in the first function, and it produces the same result, but instead of nesting the logic within itself, each piece of logic is self-contained in the form of a guard clause.</p><p>You will probably also notice that the logic is the inverse of the logic in the first function. This is an aspect of writing guard clauses that takes some getting used to. It takes a little bit more effort to write a function cleanly using guard clauses, but the little extra effort is worth it, especially when you or another developer return to your function in the future to review and update the logic.</p><p><strong>Write your Logic First, Then Refactor</strong></p><p>When you go to write your functions, it is best to write the function the long way first, using the nested conditional logic method, make sure it works, and the go back and refactor it to a cleaner, more elegant function using guard clauses.</p><p>The reason for this is because when we write out a function, it is easier to write the function to follow our thought process and how we would break the function down step by step. No programmer that I have ever met can start off by writing clean functions. The first time any programmer writes their functions, they will most likely look a lot like the first function I demonstrated. Once the function is working and does what it is intended to do, a programmer will go back and refactor it to look more like the latter example above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe4bb8788425" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>