David Walsh Blog: Recent Episodes

None

A blog featuring tutorials about JavaScript, HTML5, AJAX, PHP, CSS, WordPress, and everything else development.

View Details

As the web continues to be the medium for all users, standards bodies need to continue to provide new APIs to enrich user experience and accessibility. One underused API for unsighted users is speechSynthesis, an API to programmatically direct the browser to audibly speak any arbitrary string.

The CodeYou can direct the browser to utter speech with window.speechSynthesis and SpeechSynthesisUtterance:

window.speechSynthesis.speak( new SpeechSynthesisUtterance('Hey Jude!')) speechSynthesis.speak will robotically tell the user anything you provide as a SpeechSynthesisUtterance string. Support for this API is available in all modern browsers.

I wouldn’t consider speechSynthesis as a replacement for native accessibility tools, but this API could be used to improve what native tools provide!

The post JavaScript SpeechSynthesis API appeared first on David Walsh Blog.

View Details

Setting up a new computer is bliss — no old, unused apps and the machine performs much better than the previous. Unfortunately, you may encounter new problems based on the new hardware. One such issue I encountered with my new MacBook was a “This video format is not supported” message when I went to YouTube TV.

Not being able to watch my favorite live show is a real problem. After a bit of research, I found the solution to the “This video format is not supported” error message. To solve this problem:

  1. Open your browser settings and do a search for DRM
  2. You should see reference to Widevine, a form of DRM
  3. Enable this Widevine setting
  4. Restart your web browser

Enabling Widevine within your browser will make your YouTube TV video feed work properly. Better than needing to install a codec like the good old days, right?

The post Fix “This video format is not supported” on YouTube TV appeared first on David Walsh Blog.

View Details

Managing media is a really difficult task if you try to do all of it yourself, especially if the media comes from other sources. The file can be submitted in any state and size, but what if you need something really specific? You can code it all yourself or you can use an awesome service like Filestack, a utility to upload, transform, and deliver that media in the most optimal style imaginable!

The SetupThe first step in the Filestack journey is signing up for free. You’ll get at 21 day free trial and can cancel at any time. Once signed up, you’ll have full access to the Filestack libraries of code. You’ll also want to spend time catching up on the Filestack documentation, which is a developer’s dream — code samples and detailed usage information.

UploadAllowing your users to take advantage of easy uploading with Filestack starts with the

// Using JavaScriptconst client = filestack.init("apikey");const picker = client.picker(); picker.open(); The result is an elegant, highly functional, and feature filled file uploading UI component:

This great utility integrates with 20+ popular services like Google Drive, Dropbox, GitHub, Facebook, Instagram, and more. As the Filestack picker also illustrates, users can take advantage of the ease of dragging and dropping files to upload.

If you prefer to do your uploading on the back end, you can use the Filestack Python library:

from filestack import Clientclient = Client(APIKEY)store\_params = { 'location': 's3', 'path': 'folder/subfolder/', 'upload\_tags': { "foo":"bar" }}filelink = client.upload(filepath='path/to/filename.jpg', store\_params=store\_params) Unlike many services, Filestack provides a number of code libraries to make the developer experience much easier. With files uploaded, it’s time to transform!

TransformUsers can upload any type of file at any size or format, so the ability to quickly and easily transform file that file into something more to the developer’s liking is key. Transformations can be applied to videos, images, and even documents. Transformations can also be done on in real time or via sync workflows.

For example, you can resize and manipulate images by adjusting URL parameters:

// Resize an image to have a width of 300pxhttps://cdn.filestackcontent.com/resize=width:300/pdn7PhZdT02GoYZCVYeF// Add a color filter, rotate the image, and add a "polaroid" border to the imagehttps://cdn.filestackcontent.com/resize=width:300/sepia=tone:80/polaroid/pdn7PhZdT02GoYZCVYeF So what else can be done with transformations beside file dimension and effects? Lots!

  • Enhancing: Upscale and remove red eye effects
  • Borders & Effects: Rounded corners, vignette, polaroid, torn edges, shadows
  • Filters: Sharpen, blur, b&w, Sepia, oil paint, pixelate, and more
  • Facial Detection: detect, crop, pixelate, and blur faces
  • File Type: format conversion, animation (image to GIF), ASCII, collage, QR code, screenshot
  • Documents: PDF create and convert, document to image

All of these commands can be combined to completely transform any file into exactly what you’d like to present to your users! And if you’d prefer to have a UI for users to transform media themselves, you can!

DeliverWith the files uploaded and transforms completed, the last step is delivering to clients. That delivery is incredibly important, as reliability and fast rendering can impact user retention and business conversion.

Filestack’s CDN caches Filestack URLs the first time they are accessed, such as in the case of storage aliases or transformations. The cached copy of any unique Filestack URL will live for 30 days – it will then be re-cached only when it is requested again.

Try Filestack!Filestack’s platform is incredibly flexible, powerful, and useful. From the start of uploading, to transforming into a custom file, and delivering that file quickly, Filestack is a great platform that takes those files from start to finish; from source to consumer!

The post Easy way to upload, transform and deliver files and images (Sponsored) appeared first on David Walsh Blog.

View Details

The ability to download media on the internet almost feels like a lost art. When I was in my teens, piracy of mp3s, movies, and just about everything else via torrents and apps like Kazaa, LimeWire, Napster, etc. was in full swing. These days sites use blob URLs and other means to prevent downloads. Luckily we have tools like yt-dlp to download individual YouTube videos or entire channels of content.

To download an entire channel, you can use yt-dlp:

yt-dlp https://www.youtube.com/@beetlejuicearchives3490 If you’re like me and only care for the audio, you can use a few more arguments:

yt-dlp -x --audio-format mp3 https://www.youtube.com/@beetlejuicearchives3490 youtube-dl used to be the standard for downloading YouTube videos but yt-dlp seems to have taken the throne. YouTube has such a wealth of information on just about anything, be sure to download content for travel, long walks, or any other reason!

The post How to Download a YouTube Video or Channel appeared first on David Walsh Blog.

View Details

curl is one of those great utilities that’s been around seemingly forever and has endless use cases. These days I find myself using curl to batch download files and test APIs. Sometimes my testing leads me to using different HTTP headers in my requests.

To add a header to a curl request, use the -H flag:

curl -X 'GET' \ 'https://nft.api.cx.metamask.io/collections?chainId=1' \ -H 'accept: application/json' \ -H 'Version: 1' You can add multiple headers with multiple -H uses. Header format is usually [key]: [value].

The post How to Add a Header to a curl Request appeared first on David Walsh Blog.

View Details

CSS selectors never cease to amaze me in how powerful they can be in matching complex patterns. Most of that flexibility is in parent/child/sibling relationships, very seldomly in value matching. Consider my surprise when I learned that CSS allows matching attribute values regardless off case!

Adding a {space}i to the attribute selector brackets will make the attribute value search case insensitive:

/* case sensitive, only matches "example" */[class=example] { background: pink;}/* case insensitive, matches "example", "eXampLe", etc. */[class=example i] { background: lightblue;} The use cases for this i flag are likely very limited, especially if this flag is knew knowledge for you and you’re used to a standard lower-case standard. A loose CSS classname standard will have and would continue to lead to problems, so use this case insensitivity flag sparingly!

The post Case Insensitive CSS Attribute Selector appeared first on David Walsh Blog.

View Details

Working on a web extension that ships to an app store and isn’t immediately modifiable, like a website, can be difficult. Since you cannot immediately deploy updates, you sometimes need to bake in hardcoded date-based logic. Testing future dates can be difficult if you don’t know how to quickly change the date on your local machine.

To change the current date on your Mac, execute the following from command line:

```

Date Format: MMDDYYYYsudo date -I 06142024

``` This command does not modify time, only the current date. Using the same command to reset to current date is easy as well!

The post How to Set Date Time from Mac Command Line appeared first on David Walsh Blog.

View Details

Remembering the WiFi password when on a guest network is never easy. Even worse is when it’s no longer posted and someone else is asking you for it. Luckily there’s a built in Windows command to recover the password of a given WiFi network.

The Shell CodeOpen cmd and execute the following command:

netsh wlan show profile name="David Walsh's Network" key=clear The result of the command, assuming the network is found, is a long text output with a variety of information about the network. To get the see the password for the network, look under the “Security settings” heading which will look like this:

Security settings----------------- Authentication : WPA2-Personal Cipher : CCMP Authentication : WPA2-Personal Cipher : GCMP Security key : Present Key Content : **THE\_PLAIN\_TEXT\_PASSWORD** As with any complicated command line format, it’s best to create an alias so that you don’t need to remember the full string!

The post How to Retrieve WiFi Password on Windows appeared first on David Walsh Blog.

View Details

This past weekend I had the opportunity to be what every father wants, if only for a moment: the “cool dad”. My wife was out of town and my youngest son wanted to play PUBG. I caved in, taught him the basic FPS key binds, and he was having a great time. While he was fragging out, he pressed a bunch of random keys and ended up changing movement buttons. Suddenly the traditional WASD movement keys were useless and the arrow keys triggered movement.

Of course, this was a degradation of player experience. After struggling to figure out what my son did, I found the solution.

To restore the WASD keys as movement keys, press the FN+W key combination. You’ll switch back to WASD keys for movement and be back on top of your game!

The post How to Fix: Windows WASD Keys Reversed with Arrow Keys appeared first on David Walsh Blog.

View Details

Modals have been an important part of websites for two decades. Stacking contents and using fetch to accomplish tasks are a great way to improve UX on both desktop and mobile. Unfortunately most developers don’t know that the HTML and JavaScript specs have implemented a native modal system via the popover attribute — let’s check it out!

The HTMLCreating a native HTML modal consists of using the popovertarget attribute as the trigger and the popover attribute, paired with an id, to identify the content element:

```

This is the contents of the popover

`` Upon clicking thebutton`, the popover will open. The popover, however, will not have a traditional background layer color so we’ll need to implement that on our own with some CSS magic.

The CSSStyling the contents of the popover content is pretty standard but we can use the browser stylesheet selector’s pseudo-selector to style the “background” of the modal:

/* contents of the popover */[popover] { background: lightblue; padding: 20px;}/* the dialog's "modal" background */[popover]:-internal-popover-in-top-layer::backdrop { background: rgba(0, 0, 0, .5); } :-internal-popover-in-top-layer::backdrop represents the “background” of the modal. Traditionally that UI has been an element with opacity such to show the stacking relationship.

The post HTML popover Attribute appeared first on David Walsh Blog.

View Details

AI media creation has expanded to incredible video art and a host of other important improvements, and LimeWire is leading the way in creating an awesome interface for the average user to become an AI artist. Limewire has just released its Developer API, a method for engineers like us to create dynamic AI art on the fly!

Quick Hits* Free to sign up! * Provides methods to create a variety of quality images from any number of AI services and algorithms * Create images based on text and other images * Modify existing images to scale them, remove backgrounds, and more * Use JavaScript, PHP, Python, or any of your favorite languages * Documentation is clean and easy to understand * Very easy to get started

A simple API call is as easy as:

curl -i -X POST \ https://api.limewire.com/api/image/generation \ -H 'Authorization: Bearer MY\_API\_KEY' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' \ -H 'X-Api-Version: v1' \ -d '{ "prompt": "A beautiful princess in front of her kingdom", "aspect\_ratio": "1:1" }' You can also upscale an existing, uploaded image:

curl -i -X POST \ https://api.limewire.com/api/image/upscaling \ -H 'Authorization: Bearer MY\_API\_KEY' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' \ -H 'X-Api-Version: v1' \ -d '{ "image\_asset\_id": "116a972f-666a-44a1-a3df-c9c28a1f56c0", "upscale\_factor": 4 }' The value in creating AI art dynamically is hard to stress the enormity of for engineers and authors alike. Rather than scouring Google Images for image to match my blog post, I can use LimeWire’s API to send keywords from the article to create a representative image. Likewise, authors can feed their story to LimeWire to generate illustrations! You can even integrate the developer API into your platform for your users to employ!

Give LimeWire’s new developer API a try! LimeWire lets you create AI images where you are!

The post Get Started in AI and NFTs with the Limewire API (Sponsored) appeared first on David Walsh Blog.

View Details

Time can be a funny thing. I still remember discovering HTML, CSS, and JavaScript coding. I still remember my first college programming course. I still remember my first day at my first coding job, then my first day at my second coding job, and then my first day at Mozilla. I still remember my first day coding for MetaMask. This year marks my 20th year as a professional software engineer and it’s happened in the blink of an eye.

Every once in a while I will make an old programming reference to a much younger engineer and then realize they have no idea what I’m talking about.

I’m so old…

  • Webpage layouts were being done with <table>s and this new “CSS float” property was becoming the new standard
  • Rounded corners were achieved via images and VML hacks for Internet Explorer
  • FTP was the best way to upload websites changes
  • SVN and copying its trunk was the best versioning tool
  • alert and confirm were the standard for “modals”
  • Firebug was the best debugging tool available
  • The “standard” for getting videos to play properly was finding the right codec to install
  • ActionScript knowledge was as valuable as JavaScript knowledge
  • Dreamweaver was best in class text editor and design tool
  • XML was the future of data structures
  • Mobile-first? Mobile didn’t exist
  • Reactive navigation? How about Java Applets…
  • …or even different <img src=""> upon mouseover and mouseleave!
  • Want to code a desktop app with web tech? Try Adobe Air!
  • NPM stood for “not performant, man”
  • Voting on a poll meant the page would refresh
  • “Social media” meant HotOrNot.com
  • The love sound of the web was a 56k modem connection purrrrr
  • Disabling right-click enforced image security
  • Bitmap (.bmp) was a viable image format
  • JavaScript had a competitor called JScript
  • SpyJax’ing let you detect where your user had been
  • Cookies were the pinnacle of user tracking
  • Social media wall? It’s called a “guestbook”…
  • …and a friends list? It’s called a “web ring’
  • Search engine optimization was spamming the <title> with keywords=

Whew, those where the days. How old are you in web?

The post I’m So Old: Web Edition appeared first on David Walsh Blog.

View Details

Anyone is capable of having their caps lock key on at any given time without realizing so. Users can easily spot unwanted caps lock when typing in most inputs, but when using a password input, the problem isn’t so obvious. That leads to the user’s password being incorrect, which is an annoyance. Ideally developers could let the user know their caps lock key is activated.

To detect if a user has their keyboard’s caps lock turn on, we’ll employ KeyboardEvent‘s getModifierState method:

document.querySelector('input[type=password]').addEventListener('keyup', function (keyboardEvent) { const capsLockOn = keyboardEvent.getModifierState('CapsLock'); if (capsLockOn) { // Warn the user that their caps lock is on? }}); I’d never seen getModifierState used before, so I explored the W3C documentation to discover other useful values:

dictionary EventModifierInit : UIEventInit { boolean ctrlKey = false; boolean shiftKey = false; boolean altKey = false; boolean metaKey = false; boolean modifierAltGraph = false; boolean modifierCapsLock = false; boolean modifierFn = false; boolean modifierFnLock = false; boolean modifierHyper = false; boolean modifierNumLock = false; boolean modifierScrollLock = false; boolean modifierSuper = false; boolean modifierSymbol = false; boolean modifierSymbolLock = false;}; getModifierState provides a wealth of insight as to the user’s keyboard during key-centric events. I wish I had known about getModifier earlier in my career!

The post Detect Caps Lock with JavaScript appeared first on David Walsh Blog.

View Details

One of the HTML elements that frequently comes into collision with CSS is the img element. As we learned in Request Metrics’ Fixing Cumulative Layout Shift Problems on DavidWalshBlog article, providing image dimensions within the image tag will help to improve your website’s score. But in a world where responsive design is king, we need CSS and HTML to work together.

Most responsive design style adjustments are done via max-width values, but when you provide a height value to your image, you can get a distorted image. The goal should always be a display images in relative dimensions. So how do we ensure the height attribute doesn’t conflict with max-width values?

The answer is as easy as height: auto!

/* assuming any media query */img { /* Ensure the image doesn't go offscreen */ max-width: 500px; /* Ensure the image height is responsive regardless of HTML attribute */ height: auto;} The dance to please users and search engines is always a fun balance. CSS and HTML were never meant to conflict but in some cases they do. Use this code to optimize for both users and search engines!

The post How to Override width and height HTML attributes with CSS appeared first on David Walsh Blog.

View Details

Over 50 thousand developers visit DavidWalshBlog every month from around the world to learn JavaScript tricks and fix problems in their code. Unfortunately, some of them have a slow experience on the site.

David tracks the performance of his Core Web Vitals and overall performance with Request Metrics. Recently, we noticed that his CLS performance score was trending pretty slow for both desktop and mobile users.

Wait, what is CLS?Cumulative Layout Shift (CLS) is one of the Core Web Vital performance metrics. It doesn’t measure load time directly, instead it measures how much a page shifts while it is being loaded. You’ve definitely seen this and been annoyed by it. These shifts make a site feel slow to a user.

CLS and the rest of the Core Web Vitals are super important. Not only because they measure user experience, but also because they influence the pagerank of a site in search. And search traffic is life for bloggers, media sites, e-commerce stores, and pretty much everyone with a website.

If we can fix the site’s CLS problem, we’ll give readers a faster experience, and boost the search ranking so David can help even more people. Sounds like a great incentive, let’s figure it out.

Crashing with Google LighthouseTo find a performance problem, many developers will use a tool like Google Lighthouse. I ran a Lighthouse report on David’s site, and here’s what I got.

A perfect score! Let’s pack it up and go home.

The trouble is that Google Lighthouse is a lie. Real users won’t have this performance. That score only represents a single test, from my lightning-fast computer, in the USA, on a fast broadband connection.

David’s real users come from all over the world, on varying devices and networks, and at all times of the day. Their performance experience is far from perfect. That’s why we need to get real user monitoring for the performance, otherwise we might never know that there is a problem.

Where are the CLS problems?David has been writing for a long time and has hundreds of posts on his site. Request Metrics tracks the CLS score per page so we can zero-in on the problems.

The largest traffic page is the root page, and that has a good CLS. But many of his posts, like Play Grand Poo World and Pornhub Interview have troubling CLS scores. We can also track the elements responsible for CLS, and for most of the posts its main > article > p. That means the first paragraph of the article is the thing shifting. Why would it do that?

What is common about these posts with the worst CLS scores? Images. Images are a very common cause of CLS problems because a browser doesn’t always know how big an image is until it’s downloaded. The browser assumes it’s 0x0 until it has the image, then shifts everything around it to make room.

Posts with lots of images would shift many times as each image was downloaded and the article shifted to make room for the new content.

Using images correctly for CLSTo avoid layout shifts when using images, we need to give the browser hints about how big the images will be. The browser will use these hints to reserve space in the layout for the image when it’s finished downloading.

<img src="/path/to/image" width="300" height="100" /> Notice that the width and height are specified as their own attributes — not part of a style tag. These attributes set both a base size of the image as well as the aspect ratio to use. You can still use CSS to make the image bigger or smaller from here.

Also notice that there is no px unit specified.

Image Sizes in WordPressDavidWalsh.name is hosted on WordPress, where there are some built-in tools to do this. We can utilize wp_image_src_get_dimensions to get the dimensions of images he’s using and add them to the markup.

Proving it worksDavid made the image changes a few days ago, and we’re already seeing an improvement. CLS has dropped 20% to 0.123. We’re real close to the “Good” range of CLS now.

There’s still some issues to sort out around fonts, but that will be a story for another time and another post.

If you’re looking to improve the real performance of your site, or worried about losing your SEO juice from Core Web Vital problems, have a look at Request Metrics. It’s got the tools to track your performance and actionable tips to actually fix the problems.

Plus it’s free, so it’s got that going for it.

The post Fixing Cumulative Layout Shift Problems on DavidWalshBlog appeared first on David Walsh Blog.

View Details

Ask any software engineer and they’ll tell you that coding date logic can be a nightmare. Developers need to consider timezones, weird date defaults, and platform-specific date formats. The easiest way to work with dates is to reduce the date to the most simple format possible — usually a timestamp. To get the immediate time in integer format, you can use Date.now:

const now = Date.now(); // 1705190738870 I will oftentimes employ Date.now() in my console.log statements to differentiate likewise console.log results from each other. You could also use that date as a unique identifier for an event in a low-traffic environment.

The post Date.now() appeared first on David Walsh Blog.

View Details

User input from HTML form fields is generally provided to JavaScript as a string. We’ve lived with that fact for decades but sometimes developers need to extract numbers from that string. There are multiple ways to get those numbers but let’s rely on regular expressions to extract those numbers!

To employ a regular expression to get a number within a string, we can use \d+:

const string = "x12345david";const [match] = string.match(/(\d+)/);match; // 12345 Regular expressions are capable of really powerful operations within JavaScript; this practice is one of the easier operations. Converting the number using a Number() wrapper will give you the number as a Number type.

The post Extract a Number from a String with JavaScript appeared first on David Walsh Blog.

View Details

Streaming services have revolutionized content delivery, sending linear media companies into a panic as they watch traditional cable services decay. “Cutting the cord” is a common practice these days, but the streaming landscape isn’t perfect. We’re a decade into streaming so I wanted to share my thoughts on the state of new media: first impressions, second thoughts, and the third degree!

  • Netflix is king thanks to having first mover advantage, and making smart financial moves over the past six months, but Netflix’s content is unremarkable. Their recent wins are USA’s Suits and content licensed from Max…they need to do better
  • The biggest loser in the current streaming landscape is the sports fan. Want to watch American Football? You need YouTubeTV, Peacock, and Amazon Prime. Soccer fan? You need Peacock, ESPN Plus, Paramount Plus, and then AppleTV Plus if you care about MLS. Being a live sports fan is really, really expensive.
  • The parent companies of HBO and Showtime killed their brands with “Max” and “Paramount Plus”. HBO’s brand name and fuzzy fade in are iconic; “Max” means nothing. Part of me died with this stupid brand change.
  • Streaming services lured us in with no advertisements but they’ve learned that the ad tiers generate more revenue. Now they’re trying to price us out to get us to choose the cheaper, ad-driven tier. Smart business but I’ll pay more to avoid the ads.
  • Apple has all the resources in the world but they treat their streaming service like everything else they do: offer an unremarkable product and skate off of name. Ted Lasso was good, as was Shrinking, but everything else is filler…
  • …and charging for Killers of the Flower Moon during the holidays, then providing it for free once people are back to work, is an embarrassing money grab.
  • Amazon doesn’t offer nearly enough in exclusive content. These tech companies are half in, half out.
  • Warner Brothers Discovery licensing their content, especially the Marvel Comic Universe IP, to Netflix because they need quick cash feels like a self-own. How do you grow Max by giving your best content to a better service?
  • AppleTV’s hardware is insanely elegant to use, though I’m annoyed they didn’t commit to their gaming offering. Roku still feels like a Super Nintendo in a N64 world.
  • The free streaming options these days are awesome if you don’t want to spend money. YouTube, RokuTV, and Tubi provide loads of great content at no expense.
  • Disney Plus offer loads of great old movies but my kids rarely watch it — they’re busy watching cringe shows on Netflix…
  • One huge frustration is the lack of a “previous” button that cable remotes had. Navigating between channels in YouTubeTV is painful
  • …and to further improve the experience, it would be great if AppleTV and Roku would allow users to have two apps side by side; let us build our own multi-view.
  • Part of me wants to bin off all of my sports streaming services and simply use StreamEast…but the convenience is just too nice.

Agree or disagree? What did I miss? Let me know in the comments below!

The post Thoughts on Streaming Services: 2024 Edition appeared first on David Walsh Blog.

View Details

As the demands of the web change and developers experiment with different user experiences, the need for more native language improvements expands. Our presentation layer, CSS, has done incredibly well in improving capabilities, even if sometimes too slow. The need for native support for automatically expanding textarea elements has been long known…and it’s finally here!

To allow textarea elements to grow vertically and horizontally, add the field-sizing property with a value of content:

textarea { field-sizing: content; // default is `fixed`} The default value for field-sizing is fixed, signaling current behavior. The new behavior, content, will expand as much as possible. To constrain the size a textarea can grow, use traditional width/max-width and height/max-height properties.

The post AutoGrow Textareas with CSS appeared first on David Walsh Blog.

View Details

The underground world of creating and streaming Super Mario World-based ROM hacks continues to gain popularity. This popularity is a tribute to the creativity of gamers and the quality of the original 30 year old video game’s mechanics. Over the past decade, incredible ROM hacks like Grand Poo World 1 and 2, Invictus, and Dram World have brought joy (and horror) to the Mario community. Sure, Nintendo released Mario Maker and Mario Maker 2, but I love SMW Central patches because they allow all of us to create, much like open source.

The most anticipated hack in years, Grand Poo World 3, was just released and is taking the Super Mario World community by storm. You cannot, however, just download GPW3; due to legal reasons, and the ability to modify it further, the process takes some work. Let’s learn how to build Grand Poo World 3!

What You’ll NeedYou’ll need multiple apps and files to build and play Grand Poo World 3:

  • The Grand Poo World 3 bps file from SMWCentral
  • A clean ROM file (with .smc file extension) for Super Mario World (…Google helps; use JSRomClean to verify your file)
  • A patching utility for your OS (MultiPatch for macOS, FloatingIPS for Windows)
  • An emulator to play the resulting .smc file (OpenEmu for Mac, Snes9x for Windows)

Patching Grand Poo World 3With the files and utilities available, open the patching utility and provide the path, Super Mario World ROM File, and patched file path:

If the input files are successful, you’ll get a working .smc file for GPW3! The risk is usually the SMW ROM file, so be sure to validate it with JSRomClean.

With a successful Grand Poo World 3 created, it’s time to play!

The whole process of creating Grand Poo World 3 gives me joy due to two of my loves: video games and open source coding. SMWCentral has thousands of patches you can apply on top of and parellel to ROM hacks to implement features like retry system and loads more.

Enjoy (the pain of) Grand Poo World 3!

The post How to Play Grand Poo World 3 appeared first on David Walsh Blog.

View Details

Most developers spoil themselves with fun command line utilities to make their work easier and more efficient. One such command line helper allows developers to always show the git branch in the command line. How can you get the current branch? With this handy snippet:

git branch --show-current It’s great to keep this snippet around for any automation you may create moving forward!

The post How to Get the Current Branch Name with git appeared first on David Walsh Blog.

View Details

Visual Studio Code has taken the crown of most used text editor, at least in JavaScript spheres. VSCode is fast, feature-filled, and supports thousands of plugins to boost productivity. Developers can also tweak hundreds of settings to enrich functionality. One such feature is the autoSave feature.

A few months ago I changed my editor setup to autosave code as I type. Every app works that way, code editors should too.

I recently had to disable it briefly. Feels so backwards to explicitly press Save via cmd+s.

Here is how you can change VS Code to auto save: pic.twitter.com/qmjUBXNX35

— Christoph Nakazawa (@cpojer) October 18, 2023

To autoSave files with VS Code, you can add the following to your text editor config:

{ "files.autoSave": "afterDelay", "files.autoSaveDelay": 200} Just about every Operating System and web action is instant these days, so eliminating the need for manual save just makes sense. Big thanks to my old MooTools colleague Chris Nakazawa for calling this out!

The post AutoSave with VSCode appeared first on David Walsh Blog.

View Details

One of the best things that ever happened to t he user experience of the web has been web extensions. Browsers are powerful but extensions bring a new level of functionality. Whether it’s crypto wallets, media players, or other popular plugins, web extensions have become essential to every day tasks.

Working on MetaMask, I am thrust into a world of making everything Ethereum-centric work. One of those functionalities is ensuring that .eth domains resolve to ENS when input to the address bar. Requests to https://vitalik.ethnaturally fail, since .eth isn’t a natively supported top level domain, so we need to intercept this errant request.

// Add an onErrorOccurred event via the browser.webRequest extension APIbrowser.webRequest.onErrorOccurred.addListener((details) => { const { tabId, url } = details; const { hostname } = new URL(url); if(hostname.endsWith('.eth')) { // Redirect to wherever I want the user to go browser.tabs.update(tabId, { url: `https://app.ens.domains/${hostname}}` }); }},{ urls:[`*://*.eth/*`], types: ['main\_frame'],}); Web extensions provide a browser.webRequest.onErrorOccurred method that developers can plug into to listen for errant requests. This API does not catch 4** and 5** response errors. In the case above, we look for .eth hostnames and redirect to ENS.

You could employ onErrorOccurred for any number of reasons, but detecting custom hostnames is a great one!

The post How to Detect Failed Requests via Web Extensions appeared first on David Walsh Blog.

View Details

LimeWire was a staple of my youth. LimeWire was software that allowed users to share any type of file during the revolutionary days of file sharing. Fast forward to today and LimeWire is back, again as revolutionary software, but this time in the field of AI content publishing. From creating images to music and video, and then monetizing that media, LimeWire continues to be a hub of creativity!

Quick Hits* LimeWire has re-launched as an AI-focused content publishing & community platform * LimeWire AI Studio is now live for AI Image Generation! * Generative AI music & video coming soon! * Automatically mint AI-generated content as NFTs on the Polygon and Algorand blockchains * LimeWire has an ad-revenue sharing feature built in. Creators automatically receive up to 70% of all ad revenue! * Ad Revenue is paid monthly in $LMWR, LimeWire’s native token * Start with free tier, upgrade to two affordable paid tiers!

Ready to get started creating your own amazing AI imagery with LimeWire? After signing up for free, enter the AI Studio, choose an AI model and enter keywords into the Prompt to generate your image.

Check out the AI image generated with the following prompt: Two women, drinking wine, at dinner, talking about bitcoin, happy, modern:

The more detailed the prompt you provide, the closer to your desired vision you should get. You can also use the Negative Prompt field to include terms which the AI should avoid incorporating into the image. While the image generated above prefers a more modern design, using “cartoon” generates an animated style:

Once you’re happy with an image you’ve generated, click the image so that you can download the optimized image, and even publish it to Polygon or Algorand blockchain as an NFT:

Depending on which subscription tier you choose, you can generate as many as 10,000 images per month, faster (prioritized) image generation, 70% revenue generation, and more!

Whether you’re a crypto/NFT enthusiast or just want to create some awesome AI art, LimeWire is a really compelling art studio that gives its users the ability to easily monetize their work. AI art and a store all in one is what gives LimeWire the edge on many other AI image generators. Give LimeWire a look — you may fall in love with brand all over again!

The post Welcome to the New LimeWire: AI Media Generation (Sponsored) appeared first on David Walsh Blog.

View Details

You’ve visited countless websites, and now you’re designing your own. Stop and think for a minute about what you’ve liked and didn’t like about some of those you visited. Was it the front page, the layout in general, or the functionalities that either met with your satisfaction or turned you off? The helpful tools and […]

The post Unveiling 15+ Essential Tools & Resources for Web Designers and Agencies in 2023 (Sponsored) appeared first on David Walsh Blog.

View Details

It’s rare that I’m disappointed by the JavaScript language not having a function that I need. One such case was summing an array of numbers — I was expecting Math.sum or a likewise, baked in API. Fear not — summing an array of numbers is easy using Array.prototype.reduce!

const numbers = [1, 2, 3, 4];const sum = numbers.reduce((a, b) => a + b, 0); The 0 represents the starting value while with a and b, one represents the running total with the other representing the value to be added. You’ll also note that using reduce prevents side effects! I’d still prefer something like Math.sum(...numbers) but a simple reduce will do!

The post Sum an Array of Numbers with JavaScript appeared first on David Walsh Blog.

View Details

As more of the JavaScript developers write becomes asynchronous, it’s only natural to need to wait for conditions to be met. This is especially true in a world with asynchronous testing of conditions which don’t provide an explicit await. I’ve written about waitForever, waitForTime, and JavaScript Polling in the past, but I wanted to have […]

The post JavaScript waitFor Polling appeared first on David Walsh Blog.

View Details

One of the larger downloads when requesting a webpage are custom fonts. There are many great techniques for lazy loading fonts to improve performance for those on poor connections. By getting insight into what fonts the user has available, we can avoid loading custom fonts. That’s where queryLocalFonts comes in — an native JavaScript function […]

The post queryLocalFonts appeared first on David Walsh Blog.

View Details

Web debugging tools are so incredibly excellent these days. I remember the days where they didn’t exist and debugging was a total nightmare, even for the simplest of problems. A while back I introduced many of you to Logpoints, a way to output console.log messages without needing to change the source files. Another great breakpoint […]

The post Use XHR/fetch Breakpoints! appeared first on David Walsh Blog.

View Details

Parsing of URLs on the client side has been a common practice for two decades. The early days included using illegible regular expressions but the JavaScript specification eventually evolved into a new URL method of parsing URLs. While URL is incredibly useful when a valid URL is provided, an invalid string will throw an error […]

The post URL.canParse appeared first on David Walsh Blog.

View Details

When it comes to finding relationships between elements, we traditionally think of a top-down approach. We can thank CSS and querySelector/querySelectorAll for that relationship in selectors. What if we want to find an element’s parent based on selector? To look up the element tree and find a parent by selector, you can use HTMLElement‘s closest […]

The post JavaScript closest appeared first on David Walsh Blog.

View Details

Artificial intelligence applications have hit like a massive wave over this past year, with ChatGPT being the most prominent. ChatGPT can take any written command and suggest content to match. What better than having the power of AI content creation than doing so within your own WYSIWYG editor! That’s what Froala can provide you — […]

The post ChatGPT via WYSIWYG (Sponsored) appeared first on David Walsh Blog.

View Details

Manipulating data is core to any programming language. JavaScript is no exception, especially as JSON has token over as a prime data delivery format. One such data manipulation is reversing arrays. You may want to reverse an array to show most recent transactions, or simple alphabetic sorting. Reversing arrays with JavaScript originally was done via […]

The post JavaScript: Reverse Arrays appeared first on David Walsh Blog.

View Details

It’s been quite a while since I’ve gotten a few things off of my chest and since I’m always full of peeves and annoyances I thought it was time to unleash: One day you’re getting recruited by another crypto wallet vendor, the next their users are getting drained of funds. Dodged a bullet there… Apple […]

The post Confessions of a Web Developer XX appeared first on David Walsh Blog.

View Details

Creating screen recordings is an essential skill for web developers. Screen recordings can illustrate new features, bugs, or a variety of other ideas. I’m often asked what app I use to create screen recordings and people are shocked when I tell them Quicktime! Let’s review how to create a screen recording with with Mac’s native Quicktime!

In Short:* Open Quicktime * Choose File -> New Screen Recording * Record your screen actions * Press COMMAND+CONTROL+ESC to stop and save

Step 1: Open QuicktimeTo get started with the process of recording your screen, open the Quicktime app. The Quicktime app will immediately open a dialog to import or play a video — close that dialog as you aren’t working with existing media.

Step 2: Select File > New Screen RecordingFrom the main menu, choose File and then New Screen Recording. Doing so provides you a modifiable control to select what portion of the screen you’d like to record. It’s usually best to isolate the screen to just the important part to keep video size performant and purpose precise.

Step 3: Click the Record ButtonAfter selecting the recordable area, choose the Record button in the toolbar provided. Doing so will immediately start your recording. Go ahead and executes all of the actions you would like to capture.

Step 4: Stop and Save the RecordingWhen you’ve recorded everything you hoped to, press COMMAND+CONTROL+ESC. Pressing these keys will stop the recording and prompt you to save the screen recording to the directory of your choice.

Don’t go hunting for screen recording utilities when Apple gives you Quicktime for free! Quicktime is reliable and covers all the bases!

The post How to Create a Screen Recording with Quicktime appeared first on David Walsh Blog.

View Details

Restarting and shutting down a computer remotely is a frequent task for remote system administrators. As someone that writes many shell scripts, I also find myself automating system restarts. Let’s look at a few ways to restart Mac systems from command line!

Restart a Local MacTo restart a local Mac system from command line, you can execute:

sudo shutdown -r now Restart a Remote MacTo restart a remote Mac system, you can execute:

ssh -l {AdminSystemAddress}sudo shutdown -r now Restart at a Specific TimeYou can specify a restart at a specific time:

```

Format: sudo shutdown -r hhmm# Restart at 11:30pm local timesudo shutdown -r 2330

``` System restarts are good after massive updates or just for clearing out system resources. These command line examples should help restart a Mac locally or remotely.

The post Restart Mac From Command Line appeared first on David Walsh Blog.

View Details

Bluesky is a hot new social networking platform that functions like Twitter from Twitter’s original founder. New users are flooding into the platform as a respite from Elon Musk’s vision of Twitter and the fumbles that have happened since his takeover. Upon signing up for Bluesky, your username defaults to {yourdesiredhandle}.bsky.social, but there’s a better and more secure option.

One of Bluesky’s awesome features is the ability to base your username on a hostname’s DNS record. In short, if you control a hostname’s DNS, you can essentially verify yourself. For example, my Bluesky username is davidwalsh.name. Let’s look at how you can base your username after a domain you control!

Change Your Handle to Your DomainGo to Bluesky’s Settings page and click “change my handle”

A modal will display where you can simply change the handle but you’ll want to click “I have my own domain”:

Another modal will follow asking for the domain you’d like to use and provides you with a TXT DNS record entry you need to create on that domain’s DNS:

The DNS record above is a sample value, so I haven’t exposed any sensitive informationWith the record information provided by Bluesky, go to your DNS provider and add the TXT record with the value provided by Bluesky. After adding the record, click Verify DNS Record back at Bluesky. Once Bluesky verifies the record, your username will then be your domain!

The post How to Use Your Domain on Bluesky appeared first on David Walsh Blog.

View Details

Multipurpose themes are flexible WordPress templates that can be used to create virtually any kind of website. They are often best-sellers, and because they are so popular there are a lot of them to choose from. Too many in fact unless you have time to spare to find one that is best for you.

Where there may be an instance where a specialty theme would suit you best. You can generally count on a multipurpose WordPress theme to get the job done. Especially if you are tasked with developing a variety of websites for a variety of clients.

You can use them for developing a corporate website, eCommerce site, personal blogging site, or a portfolio. In this post, we’ve saved you time by narrowing things down 10 of the best Multipurpose WordPress themes of 2023 to make the job easier for you.

  1. Be – Multipurpose WordPress Theme with 650+ prebuilt websitesThis, the biggest multipurpose theme on the market helps you build any type of website in no time at all.

BeTheme not only keeps bigger by adding to its already more than 40 core features, it keeps on getting better as well thanks to:

  • Be’s library of 650+ customizable pre-built websites. These pre-built websites are responsive, and user and navigation friendly.
  • The new Be Builder is the fastest and most intuitive website builder for WordPress and is a pleasure to work with. Be Builder is accompanied by 3000+ easily importable pages.
  • With Be’s WooCommerce Builder you can create as many templates as you like with its single product page builder and customize store details using the Theme Options feature.
  • The Setup Wizard lets you define logos, colors, fonts, and other design options during installation.
  • Be’s Header Builder 2 lets you design any header you want, without exceptions.

Be is also Elementor ready. Click on the banner to learn more about each of BeTheme’s core features.

  1. Pro – Top WordPress ThemePro is more than your typical top WordPress theme. This advanced builder from Themeco gives you more than a glimpse of what the future of site building in WordPress is going to be like. Pro, with its endless possibilities, is already there.

  2. Cornerstone for example is according to many the most advanced website builder in WordPress. The logic behind Cornerstone was apparently out with the old and in with the new.

  3. Pro’s native Grid Editor layouts are powered by CSS Grid in a point and click interface and help you build those “impossible” looking layouts, a industry-first for WordPress themes.
  4. The header, footer, page, blog, shop, and layout builders work together as a family while Pro’s native support for dynamic content allows you to build cutting-edge web applications.

Pro is made by Themeco who has ThemeForest’s fastest selling theme of all time. Click on the banner and be prepared to be impressed.

  1. Total WordPress ThemeBuild your dream website with Total, a powerful multipurpose theme that offers tons of great features for blogs, businesses, online stores, forums, portfolios and much more.

A wealth of design options and customizer settings coupled with a selection of layout choices, navigation options, dynamic template functionality, and the popular WPBakery frontend drag and drop page builder enables Total WordPress theme users to create stunning responsive websites with ease.

  • Design options include live customizer theme settings, page builder blocks and extra modules, Post entry cards, animations, and custom backgrounds.
  • Layout options include dynamic layouts, one-page sites, page and post designs, and advanced page settings.
  • Navigation features include 8 preset header styles, local scroll menus, mobile menu styles, and a simple mega menu.

Click on the banner to see why 48,000 Total customers are happy customers.

  1. Avada – Best Selling Multipurpose WordPress ThemeWith Avada, you have unlimited powers to build anything and everything from one-page business websites to thriving online marketplaces. Everyone from first-time WordPress users to professional web designers have fallen in love with this top selling multipurpose theme.

Avada’s Fusion core addresses your need for website responsiveness, performance, and attractiveness with its –

  • Fusion theme and page options and professionally crafted design elements
  • Fusion Slider, Fusion Builder, a Mega Menu, and Dynamic Content System
  • 40+ slick one-click importable demos

Avada is optimized for speed, is 100% WooCommerce ready, and gives you complete control over your design. 750,000+ users trust Avada.

  1. Uncode – Creative & WooCommerce WordPress ThemeUncode is a pixel-perfect creative WordPress theme designed with particular attention given to flexibility and performance. It is one of Envato’s top selling themes of all time which is not surprising given its powerful website builder and other features including:

  2. 70+ Carefully crafted importable mix and match pre-made designs.

  3. The Wireframes Plugin that allows you to easily import 550+ carefully designed section templates that can be combined and modified.
  4. The Advanced Drag & Drop Product Builder, performant configurable Ajax product filters with variations swatches, and impressive shop layouts to help you build incredible WooCommerce websites.

  5. TheGem – Multipurpose WordPress WooCommerce ThemeMuch of TheGem’s popularity is undoubtedly because this creative WordPress multipurpose theme is one of the most customizable and performant themes and is a perfect choice for building any website type.

Design & marketing-focused features include:

  • 400+ premium one-click importable pre-built multi-page and one-page websites with easy editing in Elementor or WPBakery
  • TheGem Templates Builder that enables you to build headers, footers, products, cart & checkouts, mega menus, popups, and other templates.
  • WooCommerce Builder with extended WooCommerce features for building perfect online shops.

You can expect the same 5-star support TheGem’s 70,000 customers have experienced.

  1. Litho – Multipurpose Elementor WordPress ThemeLitho is a modern, creative multipurpose Elementor theme that can be used to create portfolio, blog, and eCommerce websites and any type of business site as well.

  2. Litho is WooCommerce ready and multi-lingual WPML compatible. Just add the WooCommerce plugin and you are good to go to create a brand new online store and start selling your products or services.

  3. The popular Slider Revolution plugin is included free of cost.
  4. Litho created websites experience best loading speeds and give healthy SEO results.
  5. WordPress Customizer and custom widgets in Elementor combine to make Litho a highly flexible and customizable theme.

  6. Woodmart – WooCommerce Multipurpose Theme for Any Kind of StoreThere’s no need to compromise between a beautiful store and a fast website. The WoodMart WooCommerce WordPress theme is an all-in-one solution. No plugins are required. You get everything you need in one theme.

Build your content using the popular Elementor or WPBakery page builder and 80+ prebuilt websites, plus WoodMart gives you:

  • A full AJAX shop with advanced variable products with swatches, filters by size and color, pagination, and a unique full screen search by SKU.
  • Highly customizable product page layouts and styles
  • An AJAX quick shop for any product type.

And many more customer-centric options.

  1. Blocksy – Free Premium WordPress ThemeBlocksy is a light and fast, e-Commerce and Gutenberg-ready, multi purpose WordPress theme with features that help you build and customize an online store that include –

  2. Modern and elegant starter sites and the Content Blocks module you can use to add dynamic content on any page.

  3. Compatibility with the popular Elementor, Brizy, and Beaver builders.
  4. Powerful header & footer builders, a mega-menu extension and compatibility with WooCommerce.
  5. Support for Custom Post Types and Dynamic Data.
  6. Privacy compliant by locally storing Google Fonts and blocking Google’s tracking with the Cookies Consent extension.

Blocksy also features a White-label module.

  1. Kalium – Creative Multipurpose WP ThemeKalium is a creative multipurpose theme that will get you started in building your site in 3 basic steps.

  2. Choose a starter site.

  3. Install it with a single click.
  4. Edit it live with Kalium’s unlimited styling options and Elementor or WPBakery Page Builder, the world’s best page builders.

Kalium also features unique portfolio types and options, optimized theme files with impressive page speed results and very fast loading times, the Live WooCommerce builder that previews changes in real time, and customizable Headers and Footers.

Finding the best Multipurpose WordPress theme to fit your needs is still not easy. The search itself can put your patience to the test.

In this post, we’ll save you time and make life easier for you by narrowing your choices down to 10 of the best Multipurpose WordPress themes of 2023.

The post 10 Great Multipurpose WordPress Themes (Sponsored) appeared first on David Walsh Blog.

View Details

Privacy is always incredibly important, especially with visual media where you may not have the permission of individuals in the video. If you’re filming something in public, it’s likely you’ll catch someone’s face who simply doesn’t want or need to be identified. This recently got me to thinking: what’s the easiest way to blur faces in a video via command line?

The best open source utility I found for blurring faces in a video was deface. Let’s have a look at how you can use deface to blur faces in videos!

Start by downloading Python-based via pip:

python3 -m pip install deface With deface installed, simply provide the video name and get the output file with blurred faces:

sudo deface ./sample-4k-faces-video.mp4Input: ./sample-4k-faces-video.mp4Output: ./sample-4k-faces-video\_anonymized.mp4100%|█████████████████████████████ The resulting video does an impressive job of blurring out faces of persons walking by in the original recording:

View the resulting video of persons walking down the streets of New York:

The default threshold for face recognition works very well, even on moving subjects. You can experiment with thresholds with the thresh argument, and even draw the thresholds out while debugging:

I downloaded a handful of YouTube videos using my favorite YouTube downloading utility youtube-dl and I was amazed at how well deface did on a variety of visual environments. Faces were identified at a reliable level even at default threshold!

The post How to Blur Faces in a Video from Command Line appeared first on David Walsh Blog.

View Details

The CSS language is full of small gaps which are frustrating to navigate. Between CSS properties to hide a container and its contents, there is still room for improvement. visibility: hidden keeps height and width integrity while display: none on a container hides everything. You can use .container > * to hide all contents of a container, but what if there was a better way?

There is a better way to hide the contents of an element while respecting the container’s border and dimensions. That better way is using the content-visibility property:

.my-container.contents-loading { content-visibility: hidden;} A demo of such functionality:

See the Pen Untitled by David Walsh (@darkwing) on CodePen.

Avoiding a .container > * selector by using content-visibility: hidden is so much nicer from a maintenance perspective!

The post CSS content-visibility appeared first on David Walsh Blog.

View Details

Cheating in online games is a huge issue these days — just ask anyone playing PUBG. Cheaters aren’t difficult for players to spot but vendors oftentimes don’t do enough to punish these villains. Krafton recently announced they would start banning cheaters by hardware ID, which got me thinking about how you can get a user’s hardware ID.

There’s no definitive “hardware ID” provided by a machine, but you can create your own based on how specific you want to get. The hardware ID you create can be created from multiple pieces of hardware. Let’s discover how to get important IDs of different hardware components:

```

Get information about the motherboardwmic baseboard get serialnumber#> 0JU9387_84S397K# Get information about the hard drivewmic diskdrive get serialnumber#> 1234-5678-9012-3456# Get information about the CPUwmic cpu get processorid#> J8S4332SKJ93

``` Which hardware elements of the computer to build the hardware ID is up to the developer. I prefer to use maximum punishment by checking any of the components for a banned ID. A cheater could sell one component to another player but the chances are pretty low. Regardless, take action to track users by hardware if you foresee problems!

The post How to Get a Computer’s Hardware ID appeared first on David Walsh Blog.

View Details

Managing, sorting, and manipulating data with JavaScript is a skill we’ve often delegated to third party libraries like lodash. As the JavaScript language progresses, however, these features eventually get. added to the JavaScript specification. Two such APIs for grouping of Array data are `Array.prototype.group and Array.prototype.groupToMap.

Array.prototype.groupTo group an array of objects by a given property, call the group method with function that returns the grouping string:

const teams = [ { name: "Arsenal", origin: "London", tier: "legendary" }, { name: "Manchester United", origin: "Manchester", tier: "legendary" }, { name: "Liverpool", origin: "Liverpool", tier: "legendary" }, { name: "Newcastle United", origin: "Newcastle", tier: "mid" }, // Lol, awful club { name: "Tottenham", origin: "London", tier: "lol" },];const tieredTeams = teams.group(({ tier }) => tier); The result of the array’s group is an object with keys that match the grouping key:

{ legendary: [ {name: "Arsenal", origin: "London", tier: "legendary"}, {name: "Manchester United", origin: "Manchester", tier: "legendary"}, {name: "Liverpool", origin: "Liverpool", tier: "legendary"} ], mid: [ {name: "Newcastle United", origin: "Newcastle", tier: "mid"} ], lol: [ {name: "Tottenham", origin: "London", tier: "lol"} ]} Array.prototype.groupToMapgroupToMap returns a Map instance instead of an object literal:

const tieredTeamsMap = teams.group(({ tier }) => tier);tieredTeamsMap.has('lol') // truetieredTeamsMap.get('lol') // [{name: "Tottenham", origin: "London", tier: "lol"}] As of the time of publish, group and groupToMap are only available in Safari. These two methods are crucial to data management moving forward. Whether you’re manipulating data on client or server side, these newly added native methods are much welcomed.

The post JavaScript Array Group appeared first on David Walsh Blog.

View Details

A while back I wrote an article on how to Convert Image to Data URI with JavaScript. It’s a neat trick developers can use for any number of reasons. Instead of abusing canvas, however, why not simply get the base64 data from command line?

You can use base64 and pbcopy to convert a file to base64 and copy it to the clipboard:

```

base64 gets data, pbcopy copies to clipboardbase64 -i logo.jpeg | pbcopy

``` Once you have the file data copied in base64 format, the URL format to use the data is:

```

data:{mime-type};base64,{data}data:image/jpeg;base64,/9j/4AAQSkZJRgAB......

``` While base64 data and data URIs do look cryptic, they’re useful to avoid making requests to other files. I use them when creating presentations or when I can’t count on a decent internet connection.

The post How to Get a Base64 Version of a File From Command Line appeared first on David Walsh Blog.

View Details

I’m a big fan of having as much information as I can get within the command line. I couldn’t go without knowing which git branch I’m on, for example. Another important piece of information I like having is my current battery percentage.

To get the current battery level from command line, you can run:

pmset -g batt | grep -Eo "\d+%" Since I get lost in command line for hours at a time, having the percentage present saves me the labor of shifting my eyes outside of shell. What information do you like having in your command line?

The post How to Get Mac Battery Level from Command Line appeared first on David Walsh Blog.

View Details

As much as content creators want traffic to their website, there is such thing as the wrong type of traffic. Sometimes it’s content scrapers, sometimes it’s malicious bots; either way, it’s important to know how to block problematic IPs from your site.

To block a range of IP addresses using an .htaccess file, you can use the * wildcard for pieces of the IP address:

Order Allow,DenyDeny from 219.198.*.*Allow from all You can also use a regular expression:

RewriteEngine onRewriteCond %{REMOTE\_ADDR} ^219\.198\.\.RewriteRule ^ - [F] Don’t let known attackers and problematic bots bring your website to a halt! Be quick to check your site logs and ban addresses that are causing havoc!

The post How to Block a Range of IP Addresses appeared first on David Walsh Blog.

View Details

A user’s clipboard is a “catch all” between the operating system and the apps employed on it. When you use a web browser, you can highlight text or right-click an image and select “Copy Image”. That made me think about how developers can detect what is in the clipboard.

You can retrieve the contents of the user’s clipboard using the navigator.clipboard API. This API requires user permission as the clipboard could contain sensitive data. You can employ the following JavaScript to get permission to use the clipboard API:

const result = await navigator.permissions.query({name: "clipboard-write"});if (result.state === "granted" || result.state === "prompt") { // Clipboard permissions available} With clipboard permissions granted, you query the clipboard to get a ClipboardItem instance with details of what’s been copied:

const [item] = await navigator.clipboard.read();// When text is copied to clipboard....item.types // ["text/plain"]// When an image is copied from a website...item.types // ["text/html", "image/png"] Once you know the contents and the MIME type, you can get the text in clipboard with readText():

const content = await navigator.clipboard.readText(); In the case of an image, if you have the MIME type and content available, you can use <img> with a data URI for display. Knowing the contents of a user’s clipboard can be helpful when presenting exactly what they’ve copied!

The post Detect the Content Type in the Clipboard appeared first on David Walsh Blog.

View Details

We all love beautifully styled form controls but, due to the differences between operating system displays, styling them can be painful. Due to that pain, we’ve created scores of libraries to mock these controls. Unfortunately that sometimes comes at the cost of accessibility, performance, etc.

One control that has traditionally been tough to style is the input[type=file] element. Said input variation visually contains a button and text, all being clickable. Bit of a Frankenstein’s monster if you ask me. Can we style the button part though? We can!

To style the button button portion of input[type=file], you can use ::file-selector-button:

input[type=file]::file-selector-button { border: 1px solid green; background: lightgreen;} Styling this input variant wasn’t possible when it was first introduced. WebKit first started allowing styling complex form controls, and we can’t thank them enough!

The post CSS ::file-selector-button appeared first on David Walsh Blog.

View Details

I love the Brave web browser for many reasons: ad blocking, Brave rewards, crypto integration, and even a Tor tab feature. I’ll often use the Tor feature but wanted to know how I could automated opening Tor windows from command line.

To open a Brave Tor tab, you can use the following command:

open -a "Brave Browser" --args --incognito --tor

Any time I want to remotely open a Tor tab, I can do so via a shell script. Commands are such an underused but valuable utility for apps!

The post How to Open a Tor Brave Window from Command Line appeared first on David Walsh Blog.

View Details

Many engineers like myself live in the command line, and perform actions from command line that most others would click an icon for. I’ve always found opening apps from command line on Macs painful. You need to references the Applications directory, add .app to the name, etc. I just want to open apps by name.

To open an app from any directory by its simple name, you can use the -a argument to open:

open -a Cyberduck# Works regardless of case as wellopen -a CyBeRdUcK I love -a for a command like open. Being able to open any app by name is exactly what I want!

The post How to Open an App from Anywhere on Mac Command Line appeared first on David Walsh Blog.

View Details

When I was a child, I loved looking for Waldo in the “Where’s Waldo?” book series. These days I’m a sucker for TMZ’s “What’s the Big Frigin Difference” images, where TMZ slightly changes an image and you have to spot the differences between the two. That got me to thinking — how easily could I automate diff’ing two images? This StackOverflow post was gold.

To create a diff of two similar images, we’ll use ImageMagick’s convert command line utility with a large host of configurations:

convert '(' image1.png -flatten -grayscale Rec709Luminance ')' \ '(' image2.png -flatten -grayscale Rec709Luminance ')' \ '(' -clone 0-1 -compose darken -composite ')' \ -channel RGB -combine diff.png How effective is this command with its configuration arguments? Let’s have a look:

Original ImageModified ImageDiff’ed ImageThe diff image result is pretty informative! The size of the sunglasses is clearly presented, and if you look closely, you can see one skull at the top-right of the shirt has been flipped.

Whatever your reason for wanting to identify the difference two images, ImageMagick’s convert tool is impressive. You can do a million things with ImageMagick; check out my Media tutorials to learn more awesome ways to modify images, videos, and audio!

The post How to Create a Diff of Two Images appeared first on David Walsh Blog.

View Details

The start of a new year is usually a time when we start looking for ways to make something a little better. That something could be our life, work, or what we produce. Web designers, for example, might look for ways to make their designs more interesting or effective.

In this post we will focus on 5 web design trends that are designed to help users get the most from the websites they visit and we will use 10 pre-built websites from BeTheme to demonstrate how best to implement those trends .

BeTheme is one of the world’s most popular and highly-rated WordPress Themes with 268,000+ sales and a 4.83/5 star-rating.

5 new web design trends for 2023To improve anything, you have to know what it does or how it functions and what can have an impact on its performance, whether that impact is positive or negative.

In our case, we want to have a impact on web design that will lead to improvements, which is what web design trends are expected to do. What follows is a discussion on how 5 trends designed to act in the best interests of web users can be implemented.

  1. The benefits of hoverable iconographyOne effective way of avoiding clutter is to keep the amount of text on a page to a minimum. A strategic use of icons can admirably serve that purpose – assuming users understand what the icons represent!

When a situation is encountered where an icon would serve a purpose but it is not a familiar one, it would appear to be a no-win situation. You could of course add text, but that would contribute to clutter – or would it?

Let us first start with an example of familiar icons. On the BeBiker 4 website there are three icons on the left for:

  • Shopping bag/cart
  • Search
  • Account

When these icons are used over and over again, on one website or many, users immediately understand what they represent.

How then, do you address icons that are less familiar or don’t give a user an obvious clue as to what they represent?

You could give each one a brief description, but that would require adding text – which, as you will see in the BeJeweler 2 site, is not a bad idea, but a very good one:

Hover-triggered helper text is the answer in this case, and it can have other uses as well since it can provide useful information without adding clutter. Hover-trigger helpers can increase user confidence and give those same users the impression that the website owner has their interests in mind.

  1. Use social proof to build trust Trust is an important part of relationship building, whether that relationship is personal or one a brand has with its customers. In the latter case, websites often serve as the initial touchpoints between brands and consumers and is where trust building needs to be initiated.

Using social proof to build trust is a trend many web designers will add to their skillsets in 2023.

One effective trust building approach used in website design entails a page dedicated to genuine testimonials and reviews along with a home page section that does the same, as demonstrated in the following BeDoctor site example:

BeDoctor uses three distinctive trust-building types:

  • A customer satisfaction rate
  • A customer testimonial
  • An average customer rating
  • of which the latter could be linked to a ratings platform such as Google or Yelp.

Newer businesses that lack social proof to use for trust-building may need to rely on using trust marks instead. Placing an icon next to a “Checkout” button that signifies the transaction will be secure would be one example. Another example, shown in the approach taken by BeMarketing 2, is to add context to its website claims:

In this example, the “threefold” asterisk is repeated to include a brief textual statement linking to a page where proof to the claim is documented.

  1. New mobile-specific trendsGiven rules and straightforward procedures to follow, web designers have become quite proficient at addressing mobile design needs in recent years. So much so in fact that, in those instances where designers have found a comfort zone, stagnation has set in.

Nevertheless, there remains room for improvement. In 2023 we will see greater attention paid to mobile-specific features that focus on overcoming specific frictions and obstacles.

The BeLanguage 4 pre-built website addresses one of these in its navigation design:

Note how the “Call Us” button is located at the top of the list of links, rather than at the end where it would normally appear on a desktop display. A slight change perhaps, but a helpful one for a mobile user.

The BeFurnitureStore approach takes the account, cart, and favorites icons that are normally situated at the top on a desktop display and places them on a sticky bottom banner.

The use of sticky banners is also advantageous to mobile users. As long as web designers work to continuously improve the mobile web experience, it doesn’t matter how small some of their changes might appear to be. Mobile users will gain from them.

  1. Shape texturizationSkeuomorphism was once the rage and played a dominant role in the web design world. This was at a time when web users were still getting used to the technology and skeuomorphism proved to be an extremely helpful design trend as it helped users become more and more comfortable interacting with the web.

Eventually, the trend became less and less of a requirement and eventually began to be looked upon as a source of clutter and distraction. The trashcan and camera symbols remain in use, but most other examples of this design approach have gone by the wayside.

In 2023, web designers will begin working with organic shapes by adding small, strategic textures to their designs. The BeRenovate 5 website illustrates an example of this new trend:

The rounded shapes and lines that appear in the background have a softening effect while at the same time drawing attention to the central section, making the page more interesting and engaging.

Digital texturization can also be used to draw attention to a specific area of a page. BeCoaching 3 provides an example of this effective design trend.

The two digitally textured shapes seen here are used throughout this one-page website to help direct a visitor’s eyes and attention to the areas of the page you want them to go. All of the content in the example is important, but the image on the right is key and not to be missed.

  1. Benefits of supplemental videoDifferent web users have different viewing habits, making it extremely difficult, if not impossible, to satisfy them all. Some prefer reading text or blogs. Others would rather to watch and listen to a video or a vlog.

Rather than trying to satisfy both worlds, experiment with using supplemental videos or video alternatives whenever it makes sense to do so. You’re less apt to downgrade site loading speeds, and avoiding an overreliance on autoplay videos would probably earn you some good marks from your users.

The BeBusiness 6 site’s full-width video section halfway down its home page jumps right out at you.

It could be used to summarize or expand on previous content, to show a video testimonial, or for a variety of other purposes.

A video doesn’t have to be full width to be effective. This BePregnancy hero section example includes a small cutout that features a supplemental video:

The “Play” button is instantly recognizable and gives a visitor the option of whether or not to watch the video. In this instance, the choice to watch would probably win hands down, but if the video were autoplay it would probably be looked upon as being intrusive.

Using videos sparingly and strategically makes sense. Visitor’s will likely approve, and it is easier for web designers to maintain reasonable page loading speeds.

What is your opinion of these website design trends?Website design trends have more often than not focused on background and color trends, typological experimentation, attention-getting special effects, and other approaches that, while well-intentioned and usually effective, could also be viewed as being superficial to some degree.

2023’s web design trends signify a sea change in website improvement techniques. The focus is more on trust building, responsiveness, and accessibility than on user engagement or entertainment.

Use BeTheme to build websites and you’ll discover that these new trends have already been incorporated to one degree or another in many of its 650+ pre-built sites. Good news indeed!

The post 5 Web Design Trends for 2023 That You Should Pay Attention To (Sponsored) appeared first on David Walsh Blog.

View Details

A few years back I wrote a blog post about how write a fetch Promise that times out. The function was effective but the code wasn’t great, mostly because AbortController , which allows you to cancel a fetch Promise, did not yet exist. With AbortController and AbortSignal available, let’s create a better JavaScript function for fetching with a timeout:

Much like the original function, we’ll use setTimeout to time to the cancellation but we’ll use the signal with the fetch request:

async function fetchWithTimeout(url, opts = {}, timeout = 5000) { // Create the AbortController instance, get AbortSignal const abortController = new AbortController(); const { signal } = abortController; // Make the fetch request const \_fetchPromise = fetch(url, { ...opts, signal, }); // Start the timer const timer = setTimeout(() => abortController.abort(), timeout); // Await the fetch with a catch in case it's aborted which signals an error try { const result = await \_fetchPromise; clearTimeout(timer); return result; } catch (e) { clearTimeout(timer); throw e; }};// Usagetry { const impatientFetch = await fetchWithTimeout('/', {}, 2000);}catch(e) { console.log("fetch possibly canceled!", e);} The JavaScript code above is much cleaner now that we have a proper API to cancel fetch Promise calls. Attaching the signal to the fetch request allows us to use a setTimeout with abort to cancel the request after a given amount of time.

It’s been excellent seeing AbortController, AbortSignal, and fetch evolve to make async requests more controllable without drastically changing the API.

The post fetch with Timeout appeared first on David Walsh Blog.

View Details

Form validation has always been my least favorite part of web development. You need to duplicate validation on both client and server sides, handle loads of events, and worry about form element styling. To aid form validation, the HTML spec added some new form attributes like required and pattern to act as very basic validation. Did you know, however, that you can control native form validation using JavaScript?

validityEach form element (input, for example) provides a validity property which represents a ValidityState. ValidityState looks something like this:

// input.validity{ badInput: false, customError: true, patternMismatch: false, rangeOverflow: false, rangeUnderflow: false, stepMismatch: false, tooLong: false, tooShort: false, typeMismatch: false, valid: false, valueMissing: true} Each property in the ValidityState can roughly match a specific validation issue: valueMissing would match the required attribute, tooLong and tooShort match minLength and maxLength, etc.

Checking Validity and Setting a Custom Validation MessageEach form field provides a default error message for each error type, but setting a more custom message per your application is likely better. You can use the form field’s setCustomValidity to create your own message:

// Check validityinput.checkValidity();if(input.validity.valueMissing) { input.setCustomValidity('This is required, bro! How did you forget?');} else { // Clear any previous error input.setCustomValidity('');} Simply setting the message by setCustomValidity doesn’t show the message, however.

reportValidityTo get the error to display to the user, use the form element’s reportValidity method:

// Show the error!input.reportValidity(); The error tooltip will immediately display on the screen. The following example displays the error every five seconds:

See the Pen Untitled by David Walsh (@darkwing) on CodePen.

Having hooks into the native form validation system is so valuable and I wish developers used it more. Every website has its own client side validation styling, event handling, etc. Let’s use what we’ve been provided!

The post Customizing HTML Form Validation appeared first on David Walsh Blog.

View Details

Promises have changed the landscape of JavaScript. Many old APIs have been reincarnated to use Promises (XHR to fetch, Battery API), while new APIs trend toward Promises. Developers can use async/await to handle promises, or then/catch/finally with callbacks, but what Promises don’t tell you is their status. Wouldn’t it be great if the Promise.prototype provided developers a status property to know whether a promise is rejected, resolved, or just done?

My research led me to this gist which I found quite clever. I took some time to modify a bit of code and add comments. The following solution provides helper methods for determining a Promise’s status:

// Uses setTimeout with Promise to create an arbitrary delay time// In these examples, a 0 millisecond delay is // an instantly resolving promise that we can jude status againstasync function delay(milliseconds = 0, returnValue) { return new Promise(done => setTimeout((() => done(returnValue)), milliseconds));}// Promise.race in all of these functions uses delay of 0 to// instantly resolve. If the promise is resolved or rejected,// returning that value will beat the setTimeout in the raceasync function isResolved(promise) { return await Promise.race([delay(0, false), promise.then(() => true, () => false)]);}async function isRejected(promise) { return await Promise.race([delay(0, false), promise.then(() => false, () => true)]);}async function isFinished(promise) { return await Promise.race([delay(0, false), promise.then(() => true, () => true)]);} A few examples of usage:

// Testing isResolvedawait isResolved(new Promise(resolve => resolve())); // trueawait isResolved(new Promise((\_, reject) => reject())); // false// Testing isRejectedawait isRejected(new Promise((\_, reject) => reject())); // true// We done yet?await isFinished(new Promise(resolve => resolve())); // trueawait isFinished(new Promise((\_, reject) => reject())); // true Developers can always add another await or then to a Promise to execute something but it is interesting to figure out the status of a given Promise. Is there an easier way to know a Promise’s status? Let me know!

The post How to Determine a JavaScript Promise’s Status appeared first on David Walsh Blog.

View Details

A few years ago I wrote an article about how to detect VR support with JavaScript. Since that time, a whole lot has changed. “Augmented reality” became a thing and terminology has moved to “XR”, instead of VR or AR. As such, the API has needed to evolve.

The presence of navigator.xr signals that the browser supports the WebXR API and XR devices:

const supportsXR = 'xr' in window.navigator; I really like using in for feature checking rather than if(navigator.xr), as simply invoking that could cause some initialization to take place. In future posts we’ll explore identifying and connecting to different devices.

The post Detect XR Support with JavaScript appeared first on David Walsh Blog.

View Details

Reacting to events with JavaScript is the foundation of a dynamic experiences on the web. Whether it’s a click event or another typical action, responding to that action is important. We started with assigning events to specific elements, then moved to event delegation for efficiency, but did you know you can identify elements by position on the page? Let’s look at document.elementFromPoint and document.elementsFromPoint.

The document.elementFromPoint method accepts x and y parameters to identify the top-most element at a point:

const element = document.elementFromPoint(100, 100);// If you want to know the entire element stack, you can use document.elementsFromPoint:

const elements = document.elementsFromPoint(100, 100);// [, , ] The elementFromPoint and elementsFromPoint are really helpful for experiences where developers don’t want to assign individual events. Games and entertainment sites could benefit from these functions. How would you use them?

The post Document.elementFromPoint appeared first on David Walsh Blog.

View Details

It’s one thing to know about what’s in the browser document, it’s another to have insight as to the user’s browser itself. We’ve gotten past detecting which browser the user is using, and we’re now into knowing what pieces of the browser UI users are seeing.

Browsers provide window.personalbar, window.locationbar, and window.menubar properties, with the shape of { visible : /*boolean*/} as its value:

if(window.personalbar.visible || window.locationbar.visible || window.menubar.visible) { console.log("Please hide your personal, location, and menubar for maximum screen space");} What would you use these properties for? Maybe providing a warning to users when your web app required maximum browser space. Outside of that, these properties seem invasive. What do you think?

The post Detect Browser Bars Visibility with JavaScript appeared first on David Walsh Blog.

View Details

Media queries provide a great way to programmatically change behavior depending on viewing state. We can target styles to device, pixel ratio, screen size, and even print. That said, it’s also nice to have JavaScript events that also allow us to change behavior. Did you know you’re provided events both before and after printing?

I’ve always used @media print in stylesheets to control print display, but JavaScript provides beforeprint and afterprint events:

function toggleImages(hide = false) { document.querySelectorAll('img').forEach(img => { img.style.display = hide ? 'none' : ''; });}// Hide images to save toner/ink during printingwindow.addEventListener('beforeprint', () => toggleImages(true))window.addEventListener('afterprint', () => toggleImages()); It may sound weird but considering print is very important, especially when your website is documentation-centric. In my early days of web, I had a client who only “viewed” their website from print-offs. Styling with @media print is usually the best options but these JavaScript events may help!

The post JavaScript print Events appeared first on David Walsh Blog.

View Details

When it comes to animations on the web, developers need to measure the animation’s requirements with the right technology — CSS or JavaScript. Many animations are manageable with CSS but JavaScript will always provide more control. With document.getAnimations, however, you can use JavaScript to manage CSS animations!

The document.getAnimations method returns an array of CSSAnimation objects. CSSAnimation provides a host of information about the animation: playState, timeline, effect, and events like onfinish. You can then modify those objects to adjust animations:

// Make all CSS animations on the page twice as fastdocument.getAnimations().forEach((animation) => { animation.playbackRate *= 2;});// Stop all CSS animations on the pagedocument.getAnimations().forEach((animation) => { animation.cancel();}); How could adjusting CSS animations on the fly be useful to developers? Maybe use the Battery API to stop all animations when the device battery is low. Possibly to stop animations when the user has scrolled past the animation itself.

I love the way you can use JavaScript to modify CSS animations. Developers used to need to choose between CSS and JavaScript — now we have the tools to make them work together!

The post How to Control CSS Animations with JavaScript appeared first on David Walsh Blog.

View Details

Knowing when resources are loaded is a key part of building functional, elegant websites. We’re used to using the DOMContentLoaded event (commonly referred to as “domready”) but did you know there’s an event that tells you when all fonts have loaded? Let’s learn how to use document.fonts!

The document.fonts object features a ready property which is a Promise representing if fonts have been loaded:

// Await all fonts being loadedawait document.fonts.ready;// Now do something! Maybe add a class to the bodydocument.body.classList.add('fonts-loaded'); Font files can be relatively large so you can never assume they’ve loaded quickly. One simply await from document.fonts.ready gives you the answer!

The post Detecting Fonts Ready appeared first on David Walsh Blog.

View Details

Presenting numbers in a readable format takes many forms, from visual charts to simply adding punctuation. Those punctuation, however, are different based on internationalization. Some countries use , for decimal, while others use .. Worried about having to code for all this madness? Don’t — JavaScript provides a method do the hard work for you! […]

The post How to Internationalize Numbers with JavaScript appeared first on David Walsh Blog.

View Details

As a software engineer that lives too much of his life on a computer, I like keeping my machine as clean as possible. I don’t keep rogue downloaded files and removes apps when I don’t need them. Part of keeping a clean, performant system is removing empty directories. To identify empty directories, I use the […]

The post Locate Empty Directories from Command Line appeared first on David Walsh Blog.

View Details

One of the ideological sticking points of the first JavaScript framework was was extending prototypes vs. wrapping functions. Frameworks like MooTools and Prototype extended prototypes while jQuery and other smaller frameworks did not. Each had their benefits, but ultimately all these years later I still believe that the ability to extend native prototypes is a […]

The post How to Extend Prototypes with JavaScript appeared first on David Walsh Blog.

View Details

I’ve been writing a bunch of jest tests recently for libraries that use the underlying window.crypto methods like getRandomValues() and window.crypto.subtle key management methods. One problem I run into is that the window.crypto object isn’t available, so I need to shim it. To use the window.crypto methods, you will need Node 15+. You can set […]

The post How to Use window.crypto in Node.js appeared first on David Walsh Blog.

View Details

The United States is one of the last bodies that refuses to implement the Celsius temperature standard. Why? Because we’re arrogant and feel like we don’t need to change. With that said, if you code for users outside the US, it’s important to provide localized weather data to users. Let’s took at how you can […]

The post Convert Fahrenheit to Celsius with JavaScript appeared first on David Walsh Blog.

View Details

Creating a thumbnail to represent a video is a frequent task when presenting media on a website. I previously created a shell script to create a preview video from a larger video, much like many adult sites provide. Let’s view how we can create a preview thumbnail from a video! Developers can use `ffmpeg, an […]

The post Create a Thumbnail From a Video with ffmpeg appeared first on David Walsh Blog.

View Details

JavaScript and CSS allow users to detect the user theme preference with CSS’ prefers-color-scheme media query. It’s standard these days to use that preference to show the dark or light theme on a given website. But what if the user changes their preference while using your app? To detect a system theme preference change using […]

The post Detect System Theme Preference Change Using JavaScript appeared first on David Walsh Blog.

View Details

Working on a web extension is an interesting experience — you get to taste web while working with special extension APIs. One such API is storage — the web extension flavor of persistence. Let’s explore how you can use session and local storage within your Manifest V3 web extensions! Enabling Extension Storage The extension storage […]

The post How to Use Storage in Web Extensions appeared first on David Walsh Blog.

View Details

Whenever I start to feel anxiety about a big change I’m making, I start writing more unit tests. I’ll write down my fear and then write a test that attacks, and eventually relaxes, that fear. There are two actions that I’ve been frequently using with test writing: skipping all but one test or single tests. […]

The post Skip or Only Run a Test with JavaScript Mocha appeared first on David Walsh Blog.

View Details

One quality of life improvement any developer can make for themselves is ensuring different file types open in the app they’re most proficient in. If you know me, you know I prefer accomplishing as much as possible from the command line. The duti utility allows users to determine default file type from command line. The […]

The post Determine Default App for File Type from Command Line appeared first on David Walsh Blog.

View Details

I’ve been a huge fan of the Brave web browser for years. They’re crypto-friendly, provide native ad-blocking features, and even provide Tor integration. Whenever I set up new systems, I automate Brave as the default browser. You can use the following shell command to set Brave as the default browser: open -a "Brave Browser" --args […]

The post Set Brave as Default Browser from Command Line appeared first on David Walsh Blog.

View Details

Autofilling HTML input elements is a frequent user action that can drastically improve user experience. Hell, we all autofill for our passwords and address information. But what control do we have when input elements have been autofilled? To add custom CSS styles to inputs whose contents have been autofilled by the browser, you can use […]

The post CSS :autofill appeared first on David Walsh Blog.

View Details

Despite having worked on the very complex Firefox for a number of years, I’ll always love plain old console.log debugging. Logging can provide an audit trail as events happen and text you can share with others. Did you know that chrome provides monitorEvents and monitor so that you can get a log each time an […]

The post Monitor Events and Function Calls via Console appeared first on David Walsh Blog.

View Details

One aspect of web development I’ve always loathed was working with forms. Form elements have been traditionally difficult to style due to OS and browser differences, and validation can be a nightmare. Luckily the native HTML APIs added methods for improving the form validation situation. With input[type=number] elements, you can add min and max attributes. […]

The post CSS :out-of-range appeared first on David Walsh Blog.

View Details

Rebasing is a frequent task for anyone using git. We sometimes use rebasing to branch our code from the last changes or even just to drop commits from a branch. Oftentimes when trying to push after a rebase, you’ll see something like the following: hint: Updates were rejected because the tip of your current branch […]

The post git Force Push appeared first on David Walsh Blog.

View Details

I’ve heavily promoted nvm, a Node.js version manager, over the years. Having a tool to manage multiple versions of a language interpreter has been so useful, especially due to the complexity of Node.js package management. One tip I like to give new developers is adding a .nvmrc file to their repositories. The file contents is […]

The post Specify Node Versions with .nvmrc appeared first on David Walsh Blog.

View Details

For those of you not familiar with the world of web extension development, a storm is brewing with Chrome. Google will stop support for manifest version 2, which is what the vast majority of web extensions use. Manifest version 3 sees many changes but the largest change is moving from persistent background scripts to service […]

The post How to Inject a Global with Web Extensions in Manifest V3 appeared first on David Walsh Blog.

View Details

WYSIWYG editors are one of the core components of any content management system (CMS). A well-coded, feature-filled WYSIWYG HTML editor can distinguish between a CMS users love and one they can’t stand.  While all WYSIWYG editors have a set of basic functionality, the power of plugins enhances the editing experience. Plugins allow WYSIWYG editors to […]

The post How Plugins Enhance The WYSIWYG Editing Experience (Sponsored) appeared first on David Walsh Blog.

View Details

Whether you started with the old on_____ property or addEventListener, you know that events drive user experiences in modern JavaScript. If you’ve worked with events, you know that preventDefault() and stopPropagation() are frequently used to handle events. One thing you probably didn’t know: there’s a defaultPrevented proptery on events! Consider the following block of code: […]

The post JavaScript Event.defaultPrevented appeared first on David Walsh Blog.

View Details

The vast majority of blogs, news websites, and information websites run on WordPress. While the WordPress developer team and community do their best to ensure wordPress is performant, there are a number of practices you can implement to keep your site blazing fast. Let’s look at some of them! Use Cloudinary WordPress Plugin for Media […]

The post 7 Ways to Optimize Performance for Your WordPress Site (Sponsored) appeared first on David Walsh Blog.

View Details

Working on a web extension can be kinda wild — on one side you’re essentially just coding a website, on the other side you’re limited to what the browser says you can do in the extension execution environment. One change in that environment is coming January 2023 — pushing extensions to move to manifest version […]

The post How to Get Extension Manifest Information appeared first on David Walsh Blog.

View Details

Modifying visual media via code has always been a fascination of mine. Probably because I’m not a designer and I tend to stick to what I’m good at. One visual effect I love is seeing video reversed — it provides a sometimes hilarious perspective on a given event. Take this reversed water effect for example: […]

The post How to Reverse an Animated GIF appeared first on David Walsh Blog.

View Details

A decade ago HTML and CSS added the ability to, at least signal, validation of form fields. The required attribute helped inform users which fields were required, while pattern allowed developers to provide a regular expression to match against an ‘s value. Targeting required fields and validation values with just CSS and HTML was very […]

The post CSS :optional appeared first on David Walsh Blog.

View Details

JavaScript Arrays are probably my favorite primitive in JavaScript. You can do all sorts of awesome things with arrays: get unique values, clone them, empty them, etc. What about getting a random value from an array? To get a random item from an array, you can employ Math.random: const arr = [ "one", "two", "three", […]

The post Get a Random Array Item with JavaScript appeared first on David Walsh Blog.

View Details

I’m always really excited to see new methods on JavaScript primitives. These additions are acknowledgement that the language needs to evolve and that we’re doing exciting new things. That being said, I somehow just discovered some legacy String methods that you probably shouldn’t use but have existed forever. Let’s take a look! These legacy string […]

The post Legacy String Methods for Generating HTML appeared first on David Walsh Blog.

View Details

I was recently re-reading my Interview with a PornHub Web Developer and one bit I started thinking about was the VR question and the idea of making users not just see but feel` something. The haptic feedback of VR games is what really sets them apart from your standard PC or console game. So when […]

The post Interview with an Intiface Haptics Engineer appeared first on David Walsh Blog.

View Details

Every once in a while I learn about a JavaScript property that I wish I had known about years earlier — valueAsNumber is one of them. The valueAsNumber provides the value of an input[type=number] as a Number type, instead of the traditional string representation when you get the value: /* Assuming an

View Details

Web apps are accepting numerous types of inputs, from basic text to code to imagery, files, and more. It’s important that we validate the contents we receive but if you do allow arbitrary text, it’s good to know what exactly has been submitted so you can present it properly. Enter the Code Detection API — […]

The post Advanced Code Display with Code Detection API (Sponsored) appeared first on David Walsh Blog.

View Details

For as long as developers have written CSS code, we’ve been desperate to have a method to allow styling a parent element based child characteristics. That’s not been possible until now. CSS has introduced the :has pseudo-class which allows styling a parent based on a relative CSS selector! Let’s have a look at a few […]

The post CSS :has appeared first on David Walsh Blog.

View Details

Many of the web functionalities that we rely on once lived within individual desktop applications. From office suites, games, and financial tools, all of them are now web applications; they’re just as feature packed as their desktop counterparts. In the past I’ve used a variety of JavaScript grid widgets on client sites, and each had […]

The post Flexible, Powerful DataGrad from Sencha (Sponsored) appeared first on David Walsh Blog.

View Details

It’s been a while since I’ve gotten a few things off of my chest and since I’m always full of peeves and annoyances I thought it was time to unleash: Due to the immensely negative response to any tweet about crypto from my blog account, I created a second account just for crypto musings. I’ll […]

The post Confessions of a Web Developer XIX appeared first on David Walsh Blog.

View Details

Automation is a really important skill for engineers, especially when it comes to working with various file types. The more you accept for input, and the more you automate, the better end output you can offer. Filestack’s workflows allow developers to define automated tasks using a their specialized UI. With no coding required, it’s easy […]

The post Simplify Your File Handling With Filestack Workflows (Sponsored) appeared first on David Walsh Blog.

View Details

Seemingly every website, dapp, and app offers a dark mode preference, and thank goodness. Dark mode is especially useful when I’m doing late night coding, or even worse, trading into altcoins. I’m presently working on implementing a dark theme on MetaMask and it got me to thinking: is there a way we can default to […]

The post Detect Dark Mode Preference with JavaScript appeared first on David Walsh Blog.

View Details

One of my aspects of JavaScript that drew me to it as a young developers was that its syntax was loose and I could code quickly. As you gain experience as an engineer, you start to realize that some traditional coding structure is a good thing, even if it slows you down. Using Jest or […]

The post JavaScript Class Privates appeared first on David Walsh Blog.

View Details

Readers of my blog will know that I’ve been banging the Cloudinary drum for years. Their awesome media capabilities allow users to optimally deliver images, video, and audio in any format and to any device. Performance, customization, flexibility, optimized delivery… Cloudinary makes media better for everyone. Another aspect of Cloudinary that I like? Their commitment […]

The post Easy Asset Access with the Cloudinary Media Library Browser Extension appeared first on David Walsh Blog.

View Details

Some things happen in your life at exactly the right time. It could be meeting the right person, discovering an open source project you go on to join, or even starting a blog when you’re bored with a job you don’t enjoy. All of those things happened to me at the right time and brought […]

The post I Love You, Ringo appeared first on David Walsh Blog.

View Details

There’s a common saying that adults spend more time with coworkers than family; for us software engineers, we spend more time with our text editor than our families. And why shouldn’t we? They’re our main tool to do a variety of things, and as these editors evolve, they’re capable of doing even more. UltraEdit, a […]

The post Amazing Text Editing Experiences with UltraEdit (Sponsored) appeared first on David Walsh Blog.

View Details

In the last article in this series, Awesome Git Aliases, we took a look at some awesome aliases for Git. However, the true power of Git aliases comes from writing custom scripts. These allow you to build Git commands that can do anything you can imagine. In this article, I’ll show you how you can […]

The post More Awesome Git Aliases appeared first on David Walsh Blog.

View Details

Employing setInterval for condition polling has really been useful over the years. Whether polling on the client or server sides, being reactive to specific conditions helps to improve user experience. One task I recently needed to complete required that my setInterval immediately execute and then continue executing. The conventional and best way to immediately call […]

The post Immediately Executing setInterval with JavaScript appeared first on David Walsh Blog.

View Details

One of my least favorite tasks as a software engineer is resolving merge conflicts. A simple rebase is a frequent occurrence but the rare massive conflict is inevitable when many engineers work in a single codebase. One thing that helps me deal with large rebases with many merge conflicts is flattening a branch’s commits before […]

The post How to Flatten git Commits appeared first on David Walsh Blog.

View Details

Replacing a substring of text within a larger string has always been misleading in JavaScript. I wrote Replace All Occurrences of a String in JavaScript years ago and it’s still one of my most read articles. The confusion lies in that replace only replaces the first occurrence of a substring, not all occurrences. For example: […]

The post JavaScript String replaceAll appeared first on David Walsh Blog.

View Details

There are a number of utilities required to really power a content management system and its users. One of the most important utilities is a performant, feature-rich WYSIWYG editor. We’ve always had to choose between the two exiting editors, CKEditor and TinyMCE, but now we have Froala, a next generation WYSIWYG editor from Sencha. Quick […]

The post Froala: The Next Generation WYSIWYG Editor (Sponsored) appeared first on David Walsh Blog.

View Details

Automation is a system administrator, support agent, and tech savvy person’s dream. Automating tasks via scripts remotely helps to get clients out of trouble or even the organization itself. Oftentimes big updates can require users log out. Logging a user out from command line is super easy on Macs! To log a user out of […]

The post Log a User Out from Command Line appeared first on David Walsh Blog.

View Details

Reading from and writing to the user’s clipboard can be both a very useful and dangerous capability. Used correctly and it’s a huge convenience to the user; used dubiously and the user could suffer catastrophic consequences. Imagine a wrong account number or wallet address being copied — yikes! This is why programmatic copy and pasting needs to be protected, and why the JavaScript Clipboard API requires explicit user permission to allow a website to use it.

To read to the user’s clipboard, you use the readText method:

``` const clipboardData = await navigator.clipboard.readText();

```

To write to the user’s clipboard, you use the writeText method:

``` await navigator.clipboard.writeText('');

```

The API is obviously very easy to use — each method returns a Promise so you can use async/await or then callbacks. The difficult part is striking the balance of when to use each. Unnecessary reads will feel invasive, and unnecessary writes will significantly dissolve user trust.

When may you want to write to the clipboard? Possibly after the user pastes a seed phrase, password, or credit card number into likewise named form fields.

Sure you can use the numerous libraries available to simulate this API, but know that an official API does exist. And as always, I’m teaching you how to use it — it’s up to you to ensure it’s the right time and tool for the job!

The post navigator.clipboard API appeared first on David Walsh Blog.

View Details

From the very beginning of our adventure with GraphQL, we were impressed by how great its community is. The amount of content, libraries and great tools generated by GraphQL users amazed us from the very start. The more time we spent working with GraphQL the more things we saw that could be improved to make working with it easier and better. We also knew that we wanted to give something back to its wonderful community.

The origins Three years ago we were working on quite a schema with a lot of complicated relationships, then a thought occurred to us:

“It would be nice to be able to visualize it well enough to understand all the connections.”

Yes there were several solutions on the market that would let us do that, but hey everyone knows how it works. The question always arises, why not do it differently, better, and most importantly in our own way. A few days after saying:

“OK, lets do it”

came

“What if we could build a GraphQL scheme out of visual blocks?”

and that’s how it all started. We begun with the PoC version, which included just these two functionalities, namely:

  • GraphQL schema visualization,
  • the ability to build it using viusal elements.

| The very first version of GraphQL Editor from 2018 |

Our project has been very warmly received by the GraphQL community which resulted in quickly amassing 3 000 stars on GitHub. Users were not only happy to use these two simple features but also started suggesting some cool new ones. Users were not only happy to use these two simple features but also started suggesting some cool features.

What’s new in GraphQL Editor 5.0 When we started we had a roadmap in mind which we tried to stick to, as much as it was possible. But with all the additional feedback we also kept adding features suggested by the community, which after more than 2 years has led us to the point we are at now, namely the release of GraphQL Editor 5.0.

| Many graph improvements & various view modes |

So once again we would like to thank all our users for their valuable feedback, including those that were critical, it all really helped us improve. So without further ado, let’s get into the new features.

Microservices It’s the most exciting as well as the most requested feature. What’s even more satisfying about it finally being released, is that, we’ve been trying to figure out how to tackle this one since the first release of GraphgQL Editor. GraphQL Microservices allow users instantly deploy their GraphQL backend prototypes using JavaScript or TypeScript. What’s worth mentioning is microservices is powered by our open-source library called Stucco.

Stucco is a backend engine for our microservices. Its main goal is to keep you in charge of your infrastructure decisions. No risk of vendor lock-in, no worries. With Stucco you can use TypeScript, JavaScript or Golang to create GraphQL backends & deploy them easily using:

  • GraphQL Editor Shared worker
  • Local environment
  • Docker
  • Kubernetes

You can deploy microservices directly from our built-in Live Editor (similar to those you may know from Git-based platforms), but the recommended way is to do it using graphql-editor-cli. Although microservices are great for testing and development purposes, we do not recommend using them on production as they run on very small machines with rate limit of 200 requests per minute & 1 000 000 requests per month. Additionally this feature is very much work-in-progress and is being released mostly because we need live testers to iterate on it and improve it.

| With Microservices you can deploy NodeJS GraphQL backends using JavaScript or TypeScript |

JAMStack Engine Although JAMStack was introduced a couple versions back, in this one it received a significant update. We have added TypeScript and the most popular JS library for building user interfaces support – ReactJS. Among other notable features you can find:

  • better ES modules support – j just give our Live Service a CDN URL & it will fetch all types from your server and also look for typings,
  • relative ES modules imports – now you can have user relative ES module imports inside our online code editor,
  • deployment – built-in static page deployment feature to easily show off your work to your team or a wider audience.

| JAMStack with ReactJS, TS support & easy static deployment |

GraphQL Cloud We want GraphQL Editor to become a self-sufficient IDE for GraphQL based project development. Following this goal we’re adding more and more “responsibilities” for our tools. Now you can:

  • create your own queries with ease,
  • preview easily using built-in GraphiQL,
  • save & access your work anytime you need from any device.

We have also added a proxy to support every GraphQL URL & CORS issues which frequently appear during development.

| GraphQL Cloud offers GraphiQL-like queries preview, configurable mock backend & CORS support |

Last but not least Aside from core features we have also been working on some quality of life improvements like:

  • Graph improvements – the graph module has been significantly improved:
    • node & fields creation is now much faster thanks to keyboard support,
    • relation view includes all scalar fields,
    • selected node state persists between view,
    • code editor view can be toggled anytime now,
  • Spotlight menu (CTRL/CMD + K) – spotlight menu added for easier navigation,
  • Color Themes – we have added 4 new color themes,
  • Learning center – from now on every start, you will be welcomed with recent projects and a learning center to level up your editor skills,

as well as tons of bug fixes & minor UI improvements.

| Improved graph with additional view modes |


So that’s basically what we’ve been working on for the last 12 months. I must say it feels great to be able to finally share all these new features with broaded audience (thanks David!). If your are using GraphQL already I would love to hear your feedback, if not I hope GraphQL Editor would make working with it even more efficient as:

If once you start down the GraphQL path, forever will it dominate your destiny.

The post GraphQL Editor – The Journey from Initial Release to Version 5.0 appeared first on David Walsh Blog.

View Details

Working with arrays is an essential skill in any programming language, especially JavaScript, as we continue to rely on external data APIs. JavaScript has added methods like find and `findIndex recently, but one syntax I love from languages like Python is retrieving values by negative indexes.

When you want to get the value of the last item in an array, you end up with an archaic expression:

```

const arr = ["zero", "one", "two", "three"]; const last = arr[arr.length - 1];

```

You could use pop but that modifies the array. Instead you can use at and an index, even a negative index, to retrieve values:

```

const arr = ["zero", "one", "two", "three"]; arr.at(-1); // "three" arr.at(-2); // "two" arr.at(0); // "zero"

```

at is a very little known function but useful, if only for the shorthand syntax!

The post Array.prototype.at appeared first on David Walsh Blog.

View Details

In the world of marketing and content targeting, having accurate geolocation data can be the difference between a thriving enterprise and a floundering business. Accurate data is everything, especially in the targeted marketing. When you need trustworthy geolocation data, IPWHOIS.io is a great source: fast, reliable, and accurate!

Quick Hits * Start for free, very competitive pricing * Provides information about location, currency, language, and more * Helpful documentation and code samples * Fast and secure payload delivery * Provides data in CSV, JSON, and XML formats

To use IPWHOIS, make a request to their API with the desired return format and user IP address as part of the URL:

``` curl http://ipwhois.app/json/8.8.4.4

```

Your payload will look like:

{ “ip”:”8.8.4.4″, “success”:true, “type”:”IPv4″, “continent”:”North America”, “continent_code”:”NA”, “country”:”United States”, “country_code”:”US”, “country_flag”:”https:\/\/cdn.ipwhois.io\/flags\/us.svg”, “country_capital”:”Washington”, “country_phone”:”+1″, “country_neighbours”:”CA,MX,CU”, “region”:”California”, “city”:”Mountain View”, “latitude”:37.3860517, “longitude”:-122.0838511, “asn”:”AS15169″, “org”:”Google LLC”, “isp”:”Google LLC”, “timezone”:”America\/Los_Angeles”, “timezone_name”:”Pacific Standard Time”, “timezone_dstOffset”:0, “timezone_gmtOffset”:-28800, “timezone_gmt”:”GMT -8:00″, “currency”:”US Dollar”, “currency_code”:”USD”, “currency_symbol”:”$”, “currency_rates”:1, “currency_plural”:”US dollars”, “completed_requests”:3 }

The XML endpoint provides a brilliant XML payload:

```

8.8.4.4 1 IPv4 North America NA United States US https://cdn.ipwhois.io/flags/us.svg Washington +1 CA,MX,CU California Mountain View 37.3860517 -122.0838511 AS15169 Google LLC Google LLC America/Los_Angeles Pacific Standard Time 0 -28800 GMT -8:00 US Dollar USD $ 1 US dollars 8

```

You can also specify a select collection of fields you want in the payload:

``` // http://ipwhois.app/json/8.8.4.4?objects=country,city,timezone { "country": "United States", "city": "Mountain View", "timezone": "America/Los_Angeles" }

```

Using the lang parameter, you can get localized location information:

http://ipwhois.app/json/8.8.4.4?lang=es

Another awesome bonus is the ability to use JSONP:

``` $.ajax({ method: 'GET', contentType: 'application/json', url: 'http://ipwhois.app/json/' + ip, dataType: 'json', success: function(json) { // Country code output, field "country_code" console.log(json.country_code); } });

```

IPWHOIS.io is a super simple, useful service that can help you to customize your advertising and content to the user’s location, which in turn can greatly improve your chances of conversion and user satisfaction. Give IPWHOIS.io a look when you need accurate, fast geolocation information!

The post Fast, Accurate Geolocation Data with IPWHOIS.io (Sponsored) appeared first on David Walsh Blog.

View Details

One of the first commands you learn when experimenting with command line is rm, the utility for deleting files and directories. Deletion is a core computer UI operation but operating systems use a “Trash” paradigm, where files are stored before truly deleted. With the rm utility, however, files are immediately, permanently deleted.

If you’re like me and afraid to automate permanent file deletion, you can opt for a utility named trash. This nice Node.js library moves files to the trash instead of instant deletion.

`` // Install withyarn add trash`

// Move a file to trash const trash = require('trash'); await trash('bug-report.jpg');

```

There’s also a trash-cli package for using the utility from command line:

``` yarn add trash-cli

Usage

trash unicorn.png rainbow.png trash '*.png' '!unicorn.png'

```

rm can be really harsh so having a trash utility is helpful in providing users a file deletion paradigm that they’re used to.

The post Command Line trash appeared first on David Walsh Blog.

View Details

Once a week I have to deal with a zombie process or try to start a process that’s already running on its designated port. In most cases I use macOS’s Activity Monitor to kill the process, which is time-consuming. What if we could just kill a process on a given port from command line? Well, we can!

To terminate a process on a given port, install kill-port and starting nuking those zombies via:

```

yarn global add kill-port

Kill processes on multiple ports

kill-port 6060 8000

```

If you want to programmatically kill a port that you want to ensure your app will run on, you can do that as well:

```

const kill = require('kill-port')

kill(6060, 'tcp') .then(console.log) .catch(console.log)

```

I look forward to incorporating this library into my Node.js sites so that I can clear the way for a given port and avoid zombie processes.

The post Terminate Process on a Port from Command Line appeared first on David Walsh Blog.

View Details

For better or worse, form fields have been somewhat difficult to style with CSS. Form control display is dependent upon device, operating system, and browser, so you can imagine the difficulty in making styling easy. We have slowly been given some controls over form control display, as evidenced by accent-color!

The accent-color CSS property allows us to change the accent of input, input[type=radio], and input[type=checkbox] elements!

``` input { accent-color: blue; }

input[type=checkbox] { accent-color: red; }

```

See the Pen by David Walsh (@darkwing) on CodePen.

accent-color is a lovely addition to input CSS elements. I love any CSS feature that encourages using native elements instead of shimming your own to improve branding and design. Let’s hope for more CSS features like accent-color!

The post CSS accent-color appeared first on David Walsh Blog.

View Details

The UUID identifier has been used in programming since the days a baby-faced David Walsh became a professional software engineer. My first exposure to UUIDs was via a ColdFusion app I inherited and … the less we say about that the better. In any event, I was recently surprised to see that JavaScript has the ability to create UUIDs.

Developers can use the native JavaScript crypto library to generate a UUID:

```

crypto.randomUUID() // '5872aded-d613-410e-841f-a681a6aa8d8b' crypto.randomUUID() // 'fe6c7438-a833-4c7c-9ea3-cdc84ef41dfc' crypto.randomUUID() // 'e47a03d4-5da3-4451-a2c1-265de99cc2c1' crypto.randomUUID() // '04cdadeb-0228-43db-85dc-ce7e960a6cde'

```

It’s important to remember that the UUID is not guaranteed to be unique, though the probability of repetition is incredibly low. I look forward to exploring the window.crypto API further to see what other cool things we can do!

The post How to Create a UUID in JavaScript appeared first on David Walsh Blog.

View Details

One of the big themes of the web these days is concurrency, which leads to accomplishing tasks asynchronously. In doing so, the possibility of multiple errors can occur. Instead of providing a generic error, optimally you’d provide a wealth of error information. TheAggregateError error lets developers throw multiple errors within one single Error. Let’s see how it works.

To throw a single error that represents multiple errors, let’s employ AggregateError:

``` const error = new AggregateError([ new Error('ERROR_11112'), new TypeError('First name must be a string'), new RangeError('Transaction value must be at least 1'), new URIError('User profile link must be https'), ], 'Transaction cannot be processed')

```

Throwing an AggregateError gets you the following information:

``` error instanceof AggregateError // true error.name // 'AggregateError' error.message // 'Transaction cannot be processed' error.errors // The array of errors

```

The AggregateError is incredibly useful when validating multiple sets of data; instead of throwing one error at a time, grouping them into one is ideal! AggregateError would be really useful in a Promise.any situation. Communicative, information-rich errors FTW!

The post AggregateError appeared first on David Walsh Blog.

View Details

I old enough to remember when we thought XML was going to change the programming world…then JSON saved us from that hell. Parsing and querying JSON data is fundamental task we’ve all coded for, but sometimes I just want to get some data locally with minimal fuss. I just learned of a really awesome library to do so: jq. Let’s have a look at some cool things we can do with jq!

Start by installing jq via a utility like Homebrew:

``` brew install jq

```

With Homebrew installed and a local actors.json file, let’s go to work on pulling some data!

``` // Using this JSON file: // https://raw.githubusercontent.com/algolia/datasets/master/movies/actors.json

// Get the 10th item in an array cat actors.json | jq '.[10]' // { // "name": "Dwayne Johnson", // "rating": 1568, // "image_path": "/akweMz59qsSoPUJYe7QpjAc2rQp.jpg", // "alternative_name": "The Rock", // "objectID": "551486400" // }

// Get a property from the 10th item in array // > "Dwayne Johnson"

// Get multiple items jq '.[10:12]'

// Get items up to the 12th position jq '.[:12]'

// Get items after the 12th position jq '.[12:]'

// Get an array of properties from all objects jq '.[].name' // > ["William Shatner", "Will Ferrell", ...]

// Create an object with only properties I want jq '{ name: .[].name, rating: .[].rating}'

// Built in functions! jq 'sort' jq 'length' jq 'reverse'

```

There are loads of other ways to use jq, so I highly recommend you check out JQ Select Explained: Selecting elements from JSON. I’ll keep jq handy for the foreseeable future, as it will be invaluable!

The post jq for JSON appeared first on David Walsh Blog.