/ Fred Adams (xtrp) – Full Stack Web-Developer 2020-05-27T00:00:00-07:00 Fred Adams (c) 2020 Fred Adams How to Create a Beautiful Custom Scrollbar for Your Site in Plain CSS 2020-05-27T00:00:00-07:00 /blog/2020/05/27/how-to-create-a-beautiful-custom-scrollbar-for-your-site-in-plain-css/ Custom scrollbars on the web can make a site or design stand out. They can help in portraying key design aspects of a site, whether that be a specific color or a particular style.

For example, the scrollbar at Outlook.com's web app portrays a very minimalist style. CSS-Tricks' scrollbar shows their signature orange and pink look.

Default Scrollbar vs. Custom Scrollbar with Examples

In this post, we'll be building a minimalist custom scrollbar, similar to that on the Outlook.com web app.

If you'd like to see the final result, check out the Codepen for this.

1. Setting up the HTML and CSS

We'll start with a basic container element with some placeholder text, which is the element to be scrolled. The design I wrote for this is minimal, with a blue-gray color palette.

Try Scrolling!

Lorem ipsum dolor sit amet consectetur adipisicing elit. Sunt ipsa sapiente expedita aperiam iste suscipit cum voluptates voluptatibus facilis incidunt perferendis dolore iure iusto, minima culpa id velit consequatur quae?

* {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  line-height: 1.5;
  box-sizing: border-box;
}
body {
  height: 100vh;
  background-color: #ecf0f1;
  padding: 1.5rem;
  margin: 0;
}
.container {
  background-color: #fdfdfd;
  height: 100%;
  width: 100%;
  border-radius: 6px;
  box-shadow: 0 4px 28px rgba(123,151,158,.25);
  border: 1px solid #d6dee1;
  padding: 1rem;
  overflow: scroll;
}

This looks something like this:

Step 1 Result

2. Create the Scrollbar Container and Track

Let's start with the scrollbar container. The scrollbar container encompasses the entire scrollbar, including the track (spans the full height), and the draggable scrollbar thumb.

It is selected via the webkit pseudo selector ::-webkit-scrollbar, which on its own selects all scrollbars on a site. Adding a element as a prefix in the selector allows it to only select the scrollbar in that specific element; ex: .container::-webkit-scrollbar. This is the same with all other scrollbar properties that we'll use soon.

The scrollbar container is primarily used to customize the width of the entire scrollbar, like this:

::-webkit-scrollbar {
  width: 20px;
}

Next, let's customize the track, which uses the ::webkit-scrollbar-track selector.

Note: scrollbar selectors are limited, and don't properly support several CSS properties, such as padding, margin, transition, and more. I'll explain a key workaround for one these properties soon.

The track spans the full height of the element that is being scrolled. Styling it typically means changing the its background color. Keeping with the minimalist design, we'll opt to keep the track transparent for now, and only show the scrollbar thumb (the part of the scrollbar which is clicked and dragged by the user).

::-webkit-scrollbar-track {
  background-color: transparent;
}

3. Create the Scrollbar Thumb

Now for the most important part: the scrollbar thumb. As I mentioned, the scrollbar thumb is the main part of the scrollbar which is clicked and dragged by the user. It is selected by the ::-webkit-scrollbar-thumb selector.

To begin styling this, I'll add a light-grey background to fit with the general color palette being used:

::-webkit-scrollbar-thumb {
  background-color: #d6dee1;
}

Next, let's add rounded corners with the border-radius property, just like we would any other element.

::-webkit-scrollbar-thumb {
  background-color: #d6dee1;
  border-radius: 20px;
}

Adding padding to the thumb is tricky, because the scrollbar selectors don't actually support the padding property.

The workaround here is to add a transparent border in place of the padding, and to use the background-clip: content-box statement to make sure the element includes the border inside its width and height.

::-webkit-scrollbar-thumb {
  background-color: #d6dee1;
  border-radius: 20px;
  border: 6px solid transparent;
  background-clip: content-box;
}

Here's what the scrollbar looks like now, almost done:

Step 2 Result

Fits with the design, right?

4. Add a Hover Effect

Finally, let's add a hover effect to the scrollbar thumb. Unfortunately, the transition property is not supported in most browsers for scrollbars, so that isn't an option here.

So, instead, let's just make the scrollbar thumb slightly darker when hovered, without any sort of transition.

::-webkit-scrollbar-thumb:hover {
  background-color: #a8bbbf;
}

The Scrollbar is Done!

Here's the final Codepen:

As of writing, custom scrollbars are supported on all major browsers including IE11. See the Can I Use Page for more information on browser support of custom scrollbars.

I hope you liked this post and found it useful in creating a custom scrollbar.

Thanks for scrolling.

— Fred Adams, May 27, 2020

]]>
Fred Adams
AP Test Submission Problems Show Lack of Developer Adoption of .HEIC File Type 2020-05-24T00:00:00-07:00 /blog/2020/05/24/ap-test-submission-problems-show-lack-of-developer-adoption-of-heic-file-type/ Due to lockdown and quarantine in numerous countries, this year's AP tests were moved to an online platform created by College Board, the creator of the AP program and other tests such as the SAT.

In most online AP tests this year, students were given 1-2 questions on the exam web app, and were given the option to submit either a photo of their work, a supported text file (ex: .txt, .docx), or copy and paste written text.

Millions of students in the United States and other countries took Advanced Placement tests online this year, and many of those students had problems submitting their exams on the site.

I myself am a high school student and took the AP Computer Science A test this year with the new online system, and had no issues. But I know of several students who experienced issues submitting their exams, and are taking a makeup test in June.

The .HEIC Problem

One particular problem that many students experienced was from submitting photos taken from their phone. iPhones with iOS 11 (released September 2017) or later store pictures with the newer .HEIC file extension by default, rather than the more popular .jpg or .png formats. .HEIC is a filename extension for HEIF, or High Efficiency Image File Format, which was released by MPEG, the same group which invented the .MP3 format among others.

I ran a detailed test of 500 of photos, comparing the size of each photo as a .HEIC and a .JPG, with equivalent quality. .HEIC photos were more than 50% smaller than their equivalent .JPGs. Given this, in my view, it's clear why Apple would make the decision to format photos as .HEICs by default. Many iPhone users (especially high school students) take and store hundreds of photos on their phone, and using this new format saves storage space and possibly even the cost of purchasing a phone with higher storage capacity.

.JPG to .HEIC example comparison with a 44% size reduction in .HEIC

College Board's online AP exams did not accept students submitting photos encoded with the .HEIC format. In response to the issue, College Board released a section on their Tips to Avoid Problems on Exam Day page with instructions to set the default photo format to be .JPG.

Developer Adoption of .HEICs Needs to Increase

This lack of developer adoption of .HEICs in this case caused problems with user experience. Many students were unable to submit their exams, forcing them to take makeups, and according to Forbes, a lawsuit has been filed against College Board because of some of the technical issues, demanding $500 million USD.

While the problems arising from not supporting .HEICs may not be as serious in most other sites, users who experience issues may feel annoyed and confused about why they might not be able to upload images from their iPhone.

In fact, I myself recently encountered a problem where GitHub would not display .HEIC photos on their site (example), and I was forced to download them and view them on my computer's photo viewer locally. And this lack of developer adoption is all despite the widespread use of .HEIC on iPhones and the 50% size reduction in .HEICs in comparison to other formats.

Resources for Developers in Working With and Supporting .HEICs

In converting .HEIC encoded photos to other formats, there are a few options, some of which I have listed below:

  • HEIC2ANY — JS library to convert .HEIC encoded photos to JPG, PNG, or GIF on the client side (npm // site)
  • heic-convert — Converts .HEIC encoded photos to JPG or PNG on the server side in Node.js (npm)

There are also some command line tools like imagemagick (also available as an npm package) which can process .HEIC files to other formats. imagemagick can also be used to convert popular photo formats like JPG and PNG to .HEIC, which can be helpful when trying to save storage space.

That's all for this post. I hope you found this interesting and consider adding support for .HEIC files on any sites you have which get photo(s) from the user.

Thanks for scrolling.

— Fred Adams, May 24, 2020

]]>
Fred Adams
I Built Coronavirus Live Monitor - stats, news, and WHO press releases on the virus all in one place 2020-03-21T00:00:00-07:00 /blog/2020/03/21/i-built-coronavirus-live-monitor-stats-news-and-who-press-releases-on-the-virus-all-in-one-place/ Today, I am proud to release my latest web app and project: Coronavirus (COVID-19) Live Monitor, your hub for news and information on the Coronavirus outbreak. The code can be found on the GitHub repo.

Go check it out!

Site Demo

The site includes three main sections: stats, WHO press releases and health resources, and latest news.

The stats section includes a total case count, as well as total deaths and recoveries and their percentages within the total case count.

The WHO press releases and health resources section includes a video of the latest WHO press conference about the virus and links to latest situation reports and WHO news, as well as various links to health resources such as the NHS (U.K.) and the CDC (U.S.A.).

Finally, the latest news section includes news articles about the virus from a vast array of news sources. News on the virus is also sorted into country based the user's IP address, allowing for users to read news in their own language, localized for their area.

How It Was Built (in around 2-3 days total)

If you're interested in reading specifically how this was built, I've written a detailed description of the various steps I took to take this from 0 lines of code to a working web app in the course of a few days and a few more commits to GitHub.

If you choose not to continue reading, I hope you take a look at the site if you have a chance.

If you do continue reading, I hope you find my development process interesting and check out the code on GitHub.

1. Ideas and Wireframing

Before I wrote a line of code for this project, I made sure to know exactly what I was trying to build, and which technologies I would be using.

One thing I kept in mind while working on this is the large amount of information around this epidemic. At the time of writing, it can seem almost impossible to escape headlines of the virus, whether that be scrolling through YouTube, on Instagram or Twitter, or even COVID-19 related posts on The DEV Community. This constant flow of information into people about this virus has in some cases caused a lot more panic than helpful action.

So, bearing this in mind, I decided it best to not create my own coronavirus informational content sourced from health experts, but instead just link to them as health resources, as I am not an expert myself.

My main goal with this project was simply to get something working, fast.

I drew out three sections of a basic site, one large section with a case count, another with latest news, and a larger one in the center with linking to latest W.H.O. press releases and other health resources such as the CDC (U.S.A.) and the NHS (U.K.).

I made the decision to write the site entirely in plain HTML, CSS, and JavaScript, simply because my goal was fast development speed, and I am personally very proficient and most confident with just plain HTML, CSS, and vanilla JS. One of the reasons I didn't choose a framework for this is because it is a smaller project, and the more maintainable and less-confusing aspects of frameworks had less of a positive effect in my case.

2. Setting Up the HTML and CSS

With this project, I went for a very component-like based CSS structure. Styles were reused in most places in my CSS, allowing for quicker development time.

I set up the basic HTML and CSS with the three sections I had chosen (stats, information, and latest news), and made sure to make each section a component.

Here's what that might have looked like:

In this example, the panel class was a component, styled with rounded corners, some padding, and a background color.

The site had numerous reused components, such as a panel header, a tabs system, and several more.

3. Building the News Panel

I have some experience building news aggregators in the past, for example my news site Kalva, which organizes articles from hundreds of news sources into one place, searchable and sortable by source and country.

For that site, I used NewsAPI to get articles from various sources and sort and search them. I used NewsAPI for the news panel of this site as well.

I wrote a basic JavaScript fetch script to get latest articles and headlines with the keyword "coronavirus" in them, and then display those articles in the news panel.

NewsAPI also has a feature that allows articles to be sorted by country, which I implemented in an select box in the news panel.

To display news from the user's current country, I used IPAPI to determine the user's country based on their IP address, and then displayed news from only that country.

4. Building the Cases and Stats Panel

The first thing I needed for the cases and stats panel was actual statistics. At the time of writing the code, I didn't have access to APIs like The COVID Tracking Project, so I chose to use a basic web scraping and cronjobs system.

The general idea was to scrape a site with stats every couple minutes, and then update my own site with those stats.

I would a web scraper in PHP, which upon request updated a JavaScript file with the current stats in a few global variables.

That web scraper in PHP was then requested by a Python program running locally every few minutes.

You can see specifically how I did this on the code on GitHub.

5. Building the Latest Updates and Health Resources Panel

The last panel included two tabs, one with latest updates and a press video from the W.H.O., and another with links to health resources.

For fetching the latest W.H.O. press video, I first attempted a similar system for my PHP web scraper to get the current case data.

My web scraper in PHP used a basic HTTP request to fetch HTML, and unfortunately, the W.H.O. site used client-side JavaScript code to update their press videos, client-side scripts which unfortunately a basic HTTP request in PHP cannot run.

This type of problem is becoming very common as client-side JavaScript is increasingly becoming used for significant DOM updates, particularly in the cases of frameworks like Reactjs.

To fix this, I instead used a scraping program in written in JavaScript and Node.js, with a handy web scraping tool and NPM package called Puppeteer, which allows for (invisible) Chromium windows to be opened with a specified URL, and then that URL to be scraped after the client-side scripts have run.

I connected my JavaScript code with Puppeteer to a basic Express.js server which I then requested by a Python cronjobs system that scraped the site periodically and then put the press video URL in a JavaScript file for the frontend code to see.

6. Making it Work on Mobile

After everything was done, I spent some time writing the CSS to make everything work smoothly on mobile.

On mobile, I split the entire site into three tabs: news, information, and stats. Tab functionality was written with JavaScript DOM updates, and to make sure the current tab remained the same when reloading, I used a URL hash.

The URL Hash looks something like this:

https://covid19.xtrp.io/ --> default tab
https://covid19.xtrp.io/#cases --> cases and stats tab
https://covid19.xtrp.io/#news --> news tab

One key advantage of using a URL hash is that, when a hash is updated or added, the page is not forced to reload. This allows for a seemless user experience while also making sure the page is correctly displayed on load.

A hash is easily set via the location.hash JavaScript global.

That's All For Now!

If you liked this post, check out the site and star it on GitHub!

I'll be updating this site at xtrp.io a bit more regularly in the near future as well as releasing new projects, and be sure to check out some of my other posts if you liked this one.

Thanks for scrolling.

— Fred Adams, March 21, 2020

]]>
Fred Adams
IIFE's in JavaScript Explained in 3 Minutes 2020-02-29T00:00:00-08:00 /blog/2020/02/29/iifes-in-javascript-explained-in-3-minutes/ JavaScript, like many programming languages, has implied global variables: variables which can be accessed by any function, anywhere, after they have been declared and defined, without specifying that the variable is global. For example:

// a global variable
var exampleStr = "Hello, World!"

function exampleFunction(){
    console.log(exampleStr)
}

exampleFunction();

// --> logs "Hello, World!" (contents of exampleStr global variable)

Here, a global variable was defined with the value of "Hello, World!", and the function that was called had access to that variable and logged it to the console.

Global variables may be useful for smaller sites and code examples like this one, but they can cause problems in larger-scale projects and web apps.

One of the main reasons why globals can be harmful is variable naming collisions, which occur when a function creates or references a variable whose name has already been taken by a different variable that is a global.

In this example, the variable name which has a collision is name:

var name = "Fred"

function myFunction(){
    // intended to create variable, but changed global instead
    name = "John"

    // "John"
    console.log(name);
}

// "John", not "Fred"
console.log(name);

While this is a very basic example, in programs with lots of JavaScript code, globals can become very hard to keep track of and cause serious unexpected problems which can be extremely hard to debug.

For example, Rasmus Lerdorf, the creator of the PHP programming language, worked at a company which had a very complicated bug involving globals and collisions. In order to find the bug, he printed out thousands of lines of code in paper and highlighted them until he found two globals with the same name colliding with each other, in completely unrelated places in the code. If you would like, you can hear more about this at his talk about 25 years of PHP.

IIFE's Help Fix the Globals Problem

Globals are frequently created because of code that is in the global scope, not in functions, whether those functions are explicitly defined, or used in DOM events or wrapped in a statement like setTimeout() or setInterval.

IIFEs (or Immediately-Invoked Function Expressions) allow for JavaScript code to be written within a function, but immediately call that function. All code within IIFEs should not pollute the global scope or create any globals.

Written with (function(){})() or (()=>{})()

IIFEs are written by wrapping a function in parentheses, and then calling that function like normal with ();.

Here is an example of a program without an IIFE, which pollutes the global scope:

Program Example (with IIFE)

Now, with an IIFE:

Program Example (without IIFE)

With the introduction of ES6 Arrow Functions, IIFE's can be further shortened like this:

// Without ES6:
(function(){

})();

// With ES6:
(()=>{

})();

When to Use IIFEs

In many more complex programs and web apps, it can be helpful to eliminate global variables altogether. In that case, there would be little to no global code defined — code would be defined in functions and IIFEs.

In fact, it is very common to not use global variables altogether, and JavaScript has a special literal called use strict to prevent the use of global variables and throw errors if and when they are created: see JavaScript use strict Explained in 2 Minutes.

For smaller sites and scripts, I would personally simply recommend actively trying to use IIFEs whenever possible, and limiting global code. I personally do use global variables in some basic sites for brevity, but it's important to have a clear understanding of what your code's global scope looks like and what sorts of unexpected problems could occur based on that.

I hope you enjoyed this article and found IIFEs to be something you could use in future projects and scripts.

Thanks for scrolling.

— Fred Adams, February 29, 2020

]]>
Fred Adams
Create a Reading Scroll Progress Bar for Your Blog in JavaScript and CSS 2020-02-05T00:00:00-08:00 /blog/2020/02/05/scroll-progress-bar-in-js-and-css/

Go check out Daily Developer Jokes, my latest project!

Daily Developer Jokes Website Follow Daily Developer Jokes on DEV

Here's the joke from today:

Daily Developer Jokes, Friday Feb. 5, 2020


I just recently added a fun little feature on my website at xtrp.io: a progress bar when reading blog posts. The bar would show how far users have progressed in reading a post, from 0% at the beginning to when a user finishes reading at 100%.

This little feature has become particularly popular among other blogs and Wordpress themes in recent years. For example, the popular tech publication TechCrunch uses a circular scroll progress bar, and many other sites have a similar feature. In fact, if you're reading this on xtrp.io, then you may be able to see this feature on the top of your screen!

Below is a quick tutorial and explanation of a horizontal scroll progress bar with a demo on CodePen.

Live Demo and Final CodePen

Before we start, here is a link to the final CodePen, and again, a live demo can be seen on my personal website, if you are on desktop. Here's the final result of this:

Final Demo

Writing the HTML & CSS

To start off, let's create a post container div, which will include the HTML contents of the blog post that your viewers will be reading. Within that div, we'll also include a progress bar element for the scroll progress bar.

At the beginning of the post container element, let's add the progress bar HTML, which will look like this:

Note that in this post, I'll be using the BEM Methadology for CSS classnames. You can read more about the BEM Methadology and what it is here: How I Moved a Step Closer to Clean CSS and How You Can Too (with the BEM Methodology).

The general idea here is to have the progress bar container fixed at the top of the post container, with a full width. Within that container, the actual progress bar can be resized to the correct width with JavaScript.

Progress Bar and Container Visual

Here is the basic CSS for this:

/* default CSS variables */
:root {
    --progress-color: #2ecc71;
    --progress-height: .5rem;
}

/* post container */
.post-container {
    overflow: scroll;
}

/* progress bar container */
.progress-bar-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: var(--progress-height);
}

/* progress bar */
.progress-bar-container > .progress {
    height: var(--progress-height);
    background-color: var(--progress-color);
    width: 0%;
    float: left;
}

Note that in this case, the CSS assumes that the .post-container element is the scrollable area in this case (as defined with the overflow: scroll line), but you can change this to be a different element or the body element yourself if you'd like.

I'm also using CSS variables for the progress bar height and color, so that it is easier to change the properties of the progress bar if you'd like. You can read more about CSS variables and what they are here: CSS Variables Explained in 2 Minutes with an Interactive Demo.

Here's what this looks like when I set the width to 50% for example (with example content in the post container):

50% Scroll Progress Bar Width Example

Let's Write the JavaScript for this!

For the JavaScript, I'll start by defining variables for each of the relevant HTML elements:

// variables for progress bar and post container elements
const progressContainerEl = document.querySelector(".post-container");
const progressBarEl = document.querySelector(".progress-bar-container__progress");

Creating a Function to Update the Progress Bar Width

Let's create a function which checks the current scroll position and calculates the percentage of the post read, and then set the progress bar width accordingly.

To make the scroll percentage calculation, let's divide the current scroll position (from the scrollTop property) by the full scroll height of the element (calculated with a function I got from Stack Overflow).

I then set the width style of the progress bar element to that calculated percentage.

Here's the code for that:

// function to check scroll position and update scroll progress bar accordingly
const updateScrollProgressBar = () => {
    // get full scroll height
    const scrollHeight = progressContainerEl.scrollHeight - heightInViewport(progressContainerEl);
    console.log(scrollHeight);
    // get current scroll position
    const scrollPosition = progressContainerEl.scrollTop;

    // get scroll percentage and set width of progress bar
    const scrollPercentage = (scrollPosition / scrollHeight) * 100;
    progressBarEl.style.width = scrollPercentage + "%";
}

// function to get visible height in viewport
// some code taken from user Roko C. Buljan on https://stackoverflow.com/questions/24768795/get-the-visible-height-of-a-div-with-jquery
function heightInViewport(el) {
    var elH = el.offsetHeight,
        H   = document.body.offsetHeight,
        r   = el.getBoundingClientRect(), t=r.top, b=r.bottom;
    return Math.max(0, t>0? Math.min(elH, H-t) : Math.min(b, H));
}

Calling the Function While Scrolling

To put all of this together and make everything work, we'll need to call the function everytime a user scrolls and when the page is loaded. For that, it's possible bind the function to the onscroll event of the post container, and the onload event of the window.

// bind window onload and onscroll events to update scroll progress bar width
progressContainerEl.addEventListener("scroll", updateScrollProgressBar)
progressContainerEl.addEventListener("load", updateScrollProgressBar)

We're Done!

And with that, we're finished. Here is the final CodePen:

See the Pen Scroll Progress Bar Demo by Fred Adams (@xtrp) on CodePen.

I hope you liked this post, and found this to be useful.

Thanks for scrolling.

— Fred Adams, February 5, 2020

]]>
Fred Adams
CSS Variables Explained in 2 Minutes with an Interactive Demo 2020-01-27T00:00:00-08:00 /blog/2020/01/27/css-variables-explained-with-demo/

Go check out Daily Developer Jokes, my latest project!

Daily Developer Jokes Website Follow Daily Developer Jokes on DEV

Here's the joke from today:

Daily Developer Jokes, Friday Jan. 27, 2020


CSS variables have been around for quite some time now, but are nevertheless extremely useful.

They can be defined in an element like this:

element {
    --my-variable: #555;
}

The value of a variable can be just about anything, from pixel values to colors to linear-gradients.

You can use a variable almost anywhere by wrapping it in a var function:

another-element {
    color: var(--my-variable);
}

Why Not Use a Preprocessor for Variables?

This is a very common question, as preprocessors seem to have solved the CSS variable problem even before native CSS variables existed!

However, CSS variables can be changed in real-time and aren't compiled, which means that it is possible to change the value of a CSS variable within JavaScript, and all references to that variable will be automatically changed. The example coming up uses this ability pretty well, and uses this ability of CSS variables to its advantage.

A Demo of CSS Variables in Action

One use CSS variables is the ability to use a singular variable for a site's primary color, and then allow the user to interactively change that primary color as they wish.

Here's a fun little CodePen that shows just that!

See the Pen CSS Variables Demo by Fred Adams (@xtrp) on CodePen.

Here, I use some basic JavaScript code to change the CSS variable, and thus changing the theme color of the entire page.

Other Use Cases of CSS Variables

The example above is one of the many example use cases of CSS variables. Other possible uses include:

  • Creating a CSS variable for a default font size of an element and dynamically changing that for disabled users
  • Creating a CSS variable for the height and width of an element and dynamically changing that variable in a CSS animation
  • Creating CSS variables for each of the colors on your site an dynamically changing those variables to create a "dark mode" or different theme

Browser Support & Conclusion

CSS variables are supported in all major browsers except IE, QQ, and Baidu: CanIUse Data for CSS Variables.

I hope you enjoyed this explanation and demo of CSS variables and find them to be useful in your sites. I personally use CSS variables for colors and font sizes on the several of my sites, and have found them to help keep my styles much cleaner and easier to read and refactor.

Thanks for scrolling.

— Fred Adams, January 27, 2020

]]>
Fred Adams
JavaScript `use strict` Explained in 2 Minutes 2020-01-17T00:00:00-08:00 /blog/2020/01/17/javascript-use-strict/

Go check out Daily Developer Jokes, my latest project!

Daily Developer Jokes Website Follow Daily Developer Jokes on DEV

Here's the joke from today:

Daily Developer Jokes, Friday Jan. 17, 2020


JavaScript is a very lenient language in terms of how it is interpreted. For example:

x = 5;

Is not valid JavaScript code, and should be written as var x = 5 (or const/let in ES6), but the JavaScript interpreter still allows this and gives no errors.

Simply put, in general, normal JavaScript allows for code that is badly written and includes bad syntax.

use strict Solves This Problem

Introduced in ES5, the use strict directive provides a way to tell the interpreter to turn badly written JavaScript into errors.

This forces developers to write cleaner, more organized, and more readable code in the process. In fact, use strict is used by many famous JavaScript libaries such as ReactJS, jQuery, and more.

Written with the line "use strict";

The following line is used to enable use strict in the current function scope.

"use strict";

// strict code here

Use of use strict in a specific function looks like this:

function myFunc(){
    "use strict";

    // strict code here
}

Usage in the global scope is generally not used, because strict code prevents global variables (elaborated on later).

Instead, it is common practice to use use strict within a JavaScript IIFE (immediately invoked function expression), like this:

// non-strict code here

(function(){
    "use strict";

    // strict code here
})();

// non-strict code here

The "use strict"; line is a JavaScript literal expression, ignored by versions of JavaScript that don't support it.

use strict is supported by all major browsers (see CanIUse Data).

Consider the Following Example:

Non-Strict Code Example

Is non-strict code, and creates several potential problems:

  • Creates a variable without a proper var (or let/const in ES6) declaration
  • Creates a global variable which could lead to unclean or hard-to-maintain code
  • Uses the delete keyword to delete a variable, rather than letting JavaScript's garbage collector do that automatically.

Using use strict forces that code to be written more like this:

Strict Code Example

What Exactly use strict Prevents

Below is a brief list of the main features that strict mode includes:

  • Forces proper declaration of variables (e.g. x = 1;)
  • Prevents global variables
  • Blocks repeated object property names (e.g. var obj = {p1: 5, p1: 7, p2: 9};)
  • Blocks assignment to non-writable global variables (e.g. undefined = 1;)
  • Prevents use of octal numbers (e.g. var x = 0o144;)

This is not a full list, and you can read more about the exact functionality of use strict in the Use Strict MDN Web Docs Page.

I hope you enjoyed this article and found use strict to be something you may use in the future.

Thanks for scrolling.

— Fred Adams, January 17, 2020

]]>
Fred Adams
I Built Daily Developer Jokes and the First Ever DEV Bot 2020-01-12T00:00:00-08:00 /blog/2020/01/12/daily-jokes-bot-release/ Today I am proud to release my latest project — a website and the first ever DEV bot (as far as I know), called Daily Developer Jokes.

The Daily Developer Jokes bot will post programmer humor and jokes every day at 8:00 AM (EST), both on the Daily Developer Jokes Website, and on the Daily Developer Jokes DEV Profile.

Each joke comes with a custom Daily Developer Jokes banner on DEV, and an image with the joke overlayed on the top.

This is our first joke (from today):

First Joke from Daily Developer Jokes

You can check out the official, searchable list of daily developer jokes on the Daily Developer Jokes Website.

Daily Developer Jokes runs on a set of Python programs, Node.js server(s), and several PHP servers to generate posts, get jokes, generate images for jokes, and post the final markdown files to the site and DEV profile.

For posting to DEV, the Daily Developer Jokes bot uses the DEV API along with a cronjobs system written in Python, running 24/7 on a Raspberry Pi. As far as I know, the Daily Developer Jokes DEV account is the first ever DEV bot to use the DEV API to post daily.

Go check it out!

Daily Developer Jokes Website Follow Daily Developer Jokes on DEV

I may elaborate on the way I built this project and bot in the near future (and may open source it), and I hope you enjoyed this post and the project.

Thanks for scrolling.

— Fred Adams, January 12, 2020

]]>
Fred Adams
Hello World in LOLCODE: A Very Peculiar Programming Language 2020-01-11T00:00:00-08:00 /blog/2020/01/11/hello-world-in-lolcode/
HAI 1.2
    VISIBLE "Hello, World!"
KTHXBYE

Yes, that was a "Hello, World!" program in the famous LOLCODE programming language.

LOLCODE is an esoteric programming language, a type of programming language which is defined by the Esolang Wiki as follows:

An esoteric programming language is a computer programming language designed to experiment with weird ideas, to be hard to program in, or as a joke, rather than for practical use.

Other esoteric programming languages include the famous Brainf*** programming language, Malbolge, and more.

LOLCODE was written to be programming language to mimic the "lolcats" meme which became popular in the mid-2000s, with basic syntax including words such as HAI (start program with version number) and KTHXBYE (end program).

Like many other esoteric programming languages, LOLCODE is actually very featured, and has the capability to be used to write many complex programs.

In fact, Justin Meza, the creator of the most recent LOLCODE interpreter, created httpd.lol, an HTTP server written entirely in LOLCODE.

Let's Write a Basic LOLCODE Program

First, to run actual LOLCODE programs, I'll be using the LOLCODE Repl.it Online Interpreter, although you can download the LOLCODE C Interpreter to run LOLCODE programs locally.

HAI and KTHXBYE for starting and ending programs

Every LOLCODE program starts with a HAI declaration, followed by a version number. For example:

HAI 1.2

With the HAI declaration, the end of every program must include a KTHXBYE statement, for example:

HAI 1.2

KTHXBYE

BTW and OBTW for comments

The BTW keyword introduces a single line comment, like this:

BTW this is a single line comment

Whereas the OBTW and TLDR keywords are used to start and end a multiline comment respectively, for example:

OBTW
This is a multiline comment
TLDR

VISIBLE for printing to stdout

To print text in LOLCODE, the VISIBLE keyword is used as follows:

VISIBLE "Hello, World!"

Variables with I HAS A [varname] ITZ [value]

Variables in LOLCODE are written with the syntax I HAS A [var] ITZ [value], for example:

BTW this sets the variable NAME to the value "FRED ADAMS"
I HAS A NAME ITZ "FRED ADAMS"

Variables can then be referenced later with the same name.

SMOOSH and AN for concatenation

To concatenate strings and variables, SMOOSH is used. Example is provided in basic program below.

A Basic Program to Concatenate Strings and Variables

Now, we'll combine these basic LOLCODE keywords and syntax to create a very, very basic program which concatenates strings and variables.

The Python equivalent of this would be:

name = "Fred Adams"
website = "xtrp.io"
favorite_color = "blue"

print("Hi, I am " + name + ", my website is at " + website + " and my favorite color is " + favorite_color + ".")

Which in LOLCODE is:

HAI 1.2
    OBTW
        This program creates several variables, concatenates them, and prints them.
    TLDR

    BTW create variables
    I HAS A NAME ITZ "Fred Adams"
    I HAS A WEBSITE ITZ "xtrp.io"
    I HAS A FAVORITECOLOR ITZ "blue"

    BTW concatenate with SMOOSH and AN
    VISIBLE SMOOSH "Hi, I am " AN NAME AN ", my website is at " AN WEBSITE AN " and my favorite color is " AN FAVORITECOLOR AN "."
KTHXBYE

And produces the following output successfully:

Hi, I am Fred Adams, my website is at xtrp.io and my favorite color is blue.

Note that some interpreters may require LOLCODE programs to include the STDIO library, which can be included with a CAN HAS [library]? statement.

Conclusion

I hope you enjoyed this post and found LOLCODE to be a funny yet interesting programming language. You can read more about LOLCODE and its syntax on the LOLCODE Esolang Wiki Page, and check out The LOLCODE Website.

Thanks for scrolling.

— Fred Adams, January 11, 2020

]]>
Fred Adams
3 Modern CSS Features in 2 Minutes 2020-01-03T00:00:00-08:00 /blog/2020/01/03/three-modern-css-in-two-minutes/ Title assumes ~275 WPM reading, as used on xtrp.io and DEV.to

1. Clip Paths

Clip paths allow you to "clip" elements into a shape, represented in CSS with the polygon, circle, or ellipse functions. For example:

CSS Clip Path Example

div {
    background-image: url(background.jpg);
    clip-path: polygon(0 0, 100% 0, 100% 85%, 0 100%);
}

Clip paths are written with the clip-path property for clipping element content, or the background-clip property for clipping element backgrounds.

The CSS polygon function is one of the most common for clipping, and is composed of a list of points (vertices). Each point is written as x y.

For example: 0 0 would signify the top left, whereas 100% 100% would signify the bottom right. The example above uses a point on the bottom right that is not fully at the bottom (only 85%), producing a diagonal effect.

Clip paths are especially popular in flat design for creating slanted areas as shown in the example. I use this on my personal website at xtrp.io to draw attention to background images in certain pages.

Basic clip-path usage is supported in all major browsers except Edge and IE: see CanIUse Data for Clip Paths.

You can create your own clip-paths yourself, or you can use a tool like Clippy to automatically generate clip path CSS for you.

2. Blend Modes

Blend modes allow you to blend an element's content with its parent element(s) or its background using specific methods.

Let's say you were trying to overlay a yellow color over a background image. Ordinarily:

CSS Blend Mode Example 1

div {
    background-image: linear-gradient(yellow, yellow)), url(background.jpg);
}

In this case, the yellow color and the image were simply added together to create final result. However, if we wanted to blend the yellow into the image instead of adding it, we could use a blend mode called screen:

CSS Blend Mode Example 2

div {
    background-image: linear-gradient(yellow, yellow)), url(background.jpg);
    background-blend-mode: screen;
}

Blend modes are specified in backgrounds with the background-blend-mode property, and in elements (for blending with backgrounds or parents) with the mix-blend-mode property.

Possible blend modes include: screen, multiply, hard-light, difference, and more. More information on possible blend modes and their effects can be found here on the MDN web docs.

Blend modes are supported in all major browsers except Edge and IE: see CanIUse Data for Background Blend Modes.

3. CSS Filters

CSS filters provide a vast array of options for filtering elements visually. For example:

CSS Filters Example

img {
    filter: blur(10px);
}

Other filters include: sepia, invert, grayscale, and more.

CSS filters have a vast variety of uses, for example: CSS filters have become popular in creating a dark mode effect on sites using the invert filter.

The filter property is supported in all major browsers except IE: see CanIUse Data for CSS Filters.

Thanks for reading!

I hope you enjoyed this post, and found some of the CSS features mentioned to be useful.

Thanks for scrolling.

— Fred Adams, January 3, 2019

]]>
Fred Adams
2019 Developer Rewind / Year in Review: The End of a Decade 🎉, the End of an Era? 2019-12-24T00:00:00-08:00 /blog/2019/12/24/year-in-review-2019/

In this article, I list a few key events from 2019 which highlight the numerous ways the developer world is evolving and growing going into a new year and a new decade in 2020.

TL;DR

The developer world is changing fast. New tech is quickly rendering old languages and frameworks useless, and the hype for modern fields, frameworks, and languages such as WebAssembly, AI, and hybrid app development is growing rapidly. More developers are emerging faster than ever, and this decade could mark the end of an era in programming and the start of a new one.

January 2019 — GitHub Gives Us Unlimited Private Repos, for Free!

GitHub Gives Us Unlimited Private Repos Photo

January 7, 2019: GitHub CEO Nat Friedman announces unlimited private repos for free for all GitHub users. This opens up a whole new world of opportunities for developers on GitHub for free.

In terms of Git hosting platforms, GitHub is the biggest and fastest growing, with more and more developers putting code on the site, and using it to contribute with other developers across the globe.

44 million GitHub repos were created in 2019, with over half repos created being private (calculated by cross-referencing State of the Octoverse stats and GitHub public repo data). Private repos allow developers to host their personal and hobby projects with Git on GitHub, a huge capability boosted by GitHub's move to free unlimited private repositories.

While competing platforms like GitLab and BitBucket have had unlimited private repositories before GitHub, making this change, as the leading Git hosting platform, makes private repos a given, not a privilege for all developers.

February 2019 — Google Releases its First Update to Flutter; are Hybrid Apps the Future?

Google Releases its First Update to Flutter, Hybrid App Development Framework Photo

February 27, 2019: Google releases its first update to the version 1 of Flutter, their hybrid app framework.

At first, developers looking to create mobile apps for Android and iOS had to build two separate code bases for the two platforms. But, new technologies like Flutter, NativeScript, and React Native among others are making it possible to build apps for both iOS and Android with one single code base and project, dubbed hybrid app development.

Flutter, made by Google and written in Google's newer language Dart, has gained massive traction in recent years; and the release of the first update to version 1 of Flutter may mark a serious shift to hybrid app development in the future and in 2020.

Python 2 Deprecated by 2020, The Start of a New Chapter for Python Programmers

Python 2 Deprecated by 2020 Photo

Python 2.0 was the original version of Python, released in the year 2000, almost 20 years ago. In 2006, the Python team published the first version of Python 3 to try to fix some of the problems with Python 2.

Both versions of Python have been maintained ever since, but the Python team has announced that Python 2 will not be updated as of January 1, 2020. Migrating fully to the more modern Python 3 will hopefully grow Python to be even better and popular among developers, with it currently being one of the top data science, AI/ML, and finance languages out there.

You can check out a countdown until the deprecation of Python 2.7 at pythonclock.org, and read more at the official Python 2.7 sunset page.

April 2019 — Stack Overflow 2019 Survey Results Released; is Rust the Language of the Future?

Stack Overflow 2019 Survey Results Photo

April 9, 2019: Stack Overflow releases their 2019 Survey Results, detailing statistics on developer roles, favorite language, code editor of choice, and more.

The survey revealed that Rust is the most loved language by developers in 2019. Rust is a newer compiled language, and an alternative to C++ and C, with WebAssembly support and better memory safety. Rust is marketed to be as fast as C, but does it have the potential to become a leading alternative to C in 2020? We will C.

May 2019 — Mobile Takes the Majority of Web Usage as Internet Explorer Falls to Less Than 2.5% Browser Market Share

Mobile Web Usage Shift in 2020 Photo

May 2019: Surveys show that Internet Explorer's browser market share has dropped to less than 2.5%, while mobile and tablet devices now have a majority of more than 50% usage. This indicates a move away from supporting old browsers and a move towards supporting mobile.

Could mobile support also mean a shift toward PWAs (Progressive Web Apps)? Mobile growth has been rapid, and big mobile browsers like Safari and Chrome could add even more native-like features and APIs to their browsers in 2020.

You can see more detailed information on browser and device market share at the StatCounter Global Stats.

Will Web Assembly Replace JavaScript?

Will Web Assembly Replace JavaScript? Photo

WebAssembly is a newer way to achieve native-like performance on the web, and it is growing fast. Compiled from languages like Rust and C++, WebAssembly has opened up a whole new world of opportunities to web developers, in terms of working with images, manipulating graphics, and more. WebAssembly has been previously used for graphics-intensive games using WebGL (JS web graphics API), but more and more developers are using it for other purposes. The hype is on; will it live up to its expectations?

Many senior JavaScript developers have said that WebAssembly has the potential to replace JavaScript in the next 10 years because of its much faster performance. WebAssembly is supported by most major browsers today (see CanIUse data), and web developers are increasing taking advantage of WebAssembly capabilities in their sites.

July 2019 — Microsoft Puts $1 Billion into OpenAI; is AI the Next Big Thing in Programming?

Microsoft invests $1 billion into OpenAI Photo

July 2019: Microsoft invests $1 billion into OpenAI, a company focused on building the AI of the future. Big companies today like Microsoft are investing heavily into AI and machine learning, and OpenAI is a prime example.

OpenAI is different from many AI companies and startups however, because they are focused on building Artificial General Intelligence, or AGI. AGI is AI that can learn, AI that can understand and communicate with humans, and AI that can think like humans. Microsoft's investment in OpenAI could symbolize a move towards AI and AGI in the near future.

October 2019 — Hacktoberfest Takes the Developer Community By Storm; is Open Source Taking Over?

Hacktoberfest Takes the Developer Community By Storm Photo

October 1, 2019: Hacktoberfest begins! Sponsored by The DEV Community, Hacktoberfest was one month for developers to make four PRs and contribute to open source, and collect their free swag. Hacktoberfest 2019 was a huge success for open source and proves the power of open source and what it can achieve.

Hundreds of widely-used projects are open sourced, such as Linux, Node.js, and so many frameworks, libraries, websites, apps, and even programming languages. Some have said that certain open source projects are more productive than even some companies’ codebases. Hacktoberfest 2019 overall grew the open source community substantially, and gave thousands of developers a shirt to be proud of.

2020 — Development is Better Than Ever

Developing is changing rapidly as the decade comes to a close. The hype for AI and machine learning is bigger than ever, open source is growing fast, and new languages like Rust are gaining quick traction, with older languages and technologies falling away with such immense growth and change.

So much has happened in 2019 and in the last decade, and development is better than ever. The developer community is growing, open source is winning, and exciting new tech is being released constantly.

What a time to be a developer!

I hope you enjoyed this article and found it to be insightful about the future of development as a whole. Of course, everything written is based on my own opinion and research, and all these exciting changes and possibilities are only tentative; it is impossible to predict the future, but I hope this opened your eyes up about new and upcoming technologies that could make a serious impact on devs in 2020.

I wish everyone reading happy holidays and a wonderful New Year 🎉!

Thanks for scrolling.

— Fred Adams, December 24, 2019

]]>
Fred Adams
5 Strange Yet Funny Things That Only Happen in JavaScript 2019-12-15T00:00:00-08:00 /blog/2019/12/15/strange-things-in-js/

JavaScript is a tricky language and can be very confusing in terms of how its code is parsed and run. It’s an object-oriented language, but for many years it never had classes. It was built for the browser, but now it can also run on a server and work with the filesystem.

Over the years, I have seen some peculiar and equally funny code examples that will only work with JavaScript. Here are five of them.

#1: Array Concatenation Returns a String

JavaScript concatenation can get confusing sometimes. Concatenating arrays with the + operator is a prime example.

JavaScript array concatenation result

This happens because JavaScript converts both arrays to Strings and then concatenates them like this:

[1, 2, 3, 4] + [5, 6, 7, 8]

// is interpreted as:

"1,2,3,4" + "5,6,7,8"

// which yields:

"1,2,3,45,6,7,8"

#2: BaNaNa?

This is a really popular example of JavaScript inferred type when concatenating values.

BaNaNa JavaScript example

This is why this happens:

"b" + "a" + + "a" + "a" 

// is interpreted as:

"b" + "a" + (+"a") + "a"

// (+"a") is interpreted as numeric because of the starting +,
// but "a" cannot be converted to a Number, so it is NaN (not a number):

"b" + "a" + NaN + "a"

// NaN is converted to a String during concatenation, making it "NaN":

"b" + "a" + "NaN" + "a"

// String concatenation:

"baNaNa"

#3: This is VALID JavaScript Code (dubbed JSF***)

[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[]
)[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[
][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(
[][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(
![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(
!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!
![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][
[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(
![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+
[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]
])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!

Full code too long to display, see jsf___example.js for full code

Yes, that was valid JavaScript code. Try running it in the console, it will yield:

Code Result: "JavaScript is Confusing" logged to console

It turns out that any JavaScript function, String, variable, or data type can be represented with the combination of 6 characters in JS, and produces completely valid, out-of-the-box JavaScript code. This idea was dubbed as JSF*** after the Brainf*** programming language.

You can read more about JSF*** in this GitHub repo.

#4: You can write HTML Comments in JavaScript?

HTML comments are completely valid in JavaScript, and can be used in place of regular // or /* */ comments. In fact, and all do nothing in JavaScript and are ignored.

HTML comments in JavaScript example

Many JavaScript syntax highlighters do not have this interpreted, so, although amusing, it may not be practical to start using HTML comments fulltime in your JS.

This exists because HTML comments were used inside