Author: drweb

Last updated: December 13, 2023. An item in an array can be moved to its beginning by: Checking if item exists in the array (to prevent an unhandled error) Filtering the array of that value Inserting the item at the beginning of the array Here is an example in code: const array = [“Second”, “Third”, “First”]; // Check if a value exists… if (array.includes(“First”)) { //…filter this value from the array… const arrayFiltered = array.filter((val) => val !== “First”); //…and place it first in a new array, spreading the other values afterwards const res = [“First”, …arrayFiltered]; console.log(res); // […

Read More

Last updated: December 15, 2023. You can play an audio file in JavasScript by creating an Audio object, setting a URL and then calling the play() method on it: const audio = new Audio(); // Generates new Audio object, equivalent of HTML element but in JS audio.src = “https://openjavascript.info/2023/12/15/how-to-play-audio-in-javascript/./happy.mp3”; // Set URL to audio file to play audio.play(); // Play audio (usually generates error because user has not interacted with page) To prevent an error occurring when calling play() because the user has not interacted with the page, you can call it in response to a click event: Play The…

Read More

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()…

Read More

Last updated: December 28, 2023. Consider the following HTML markup: With the following styles applied via a CSS stylesheet: .content { width: 200px; height: 200px; background-color: #a52a2a; } In JavaScript, the styles applied to the with the class name of content can be accessed using the globally available getComputedStyle() function. The function accepts a HTML element and returns all its styling in object format: // Select element to retrieve styling from: const contentDiv = document.querySelector(‘.content’); // Pass element into getComputedStyle() const contentDivStyles = getComputedStyle(contentDiv); console.log(contentDivStyles); // CSSStyleDeclaration {…} Individual CSS styles can be accessed by querying properties on the CSSStyleDeclaration object…

Read More

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…

Read More

The W3C’s Mike[tm] Smith (AKA @sideshowbarker) is the man with his head in the W3C validation markup checking tool source code; he makes the magic happen.  Questions were asked for the HTML5 Doctor reader’s delight and edification. Russian Translation: Не проверив HTML5-кода, не суйся в воду — с Майком™ Смитом First off tell us a bit about what you do and what you work on Mike[tm] Smith – Deputy Director @W3C – permissive work mode edition I don’t work. I’m an old-world boulevardier. I drink tea with my pinky extended and I only expend effort on anything if it somehow amuses me to do so. For…

Read More

Images make websites look great, but they’re also the biggest performance bottleneck. They add huge file sizes, delay Largest Contentful Paint (LCP), and can even mess with Cumulative Layout Shift (CLS) if they aren’t handled properly. And while developers are quick to optimize JavaScript and CSS, images are often ignored—despite being the heaviest assets on most pages. So, how do we make images fast, responsive, and efficient? Here’s how: Choose the Right Image Format The format of an image has a massive impact on its size and loading speed. Picking the wrong one can easily double or triple your image payload. Check out this illustration:  To the user, it’s the exact same image,…

Read More

There is a ::selection pseudo class selector in CSS that allows you to style what content (mostly: text) looks like when it’s selected. Say your website has pretty strong orange-colored branding, you could use this to extend the feel of that branding. Like: html { –brandColor: orange; } ::selection { background-color: var(–brandColor); }Code language: CSS (css) There is really only a couple of things you can set on ::selection (see the allowable properties bit on MDN), which makes sense. You wouldn’t want to be changing font-size on selection or anything like that as it would get messy quickly. I was…

Read More

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:…

Read More

Updated: 3rd August 2020 The question of whether HTML elements need the addition of ARIA role attributes to expose their semantics, is one that surfaces on a regular basis. The answer is maybe for a subset of elements, but increasingly no. Patrick Lauke modelling last seasons must have; HTML5 casual Polo neck with lumbar support [button] belt and [role] braces combo. ARIA roles add nothing to default semantics of most elements In some cases the semantics of a HTML element can be expressed by an ARIA role, state or property. This is fiendishly known as the element’s ‘Default Implicit ARIA…

Read More