Author: drweb

Last updated: December 12, 2023. Most often when defining a function, you are aware of how many arguments the function should accept: function add(x, y) { return x + y; }; add(1, 2); // Returns 3 The number of arguments accept can be extended manually: function add(x, y, z=0) { return x + y + z; }; add(1, 2); // Returns 3 add(1, 2, 3); // Returns 6 But this solution isn’t very scalable because you have to include a parameter in the function for each argument you may pass in when the function is called. A solution is to…

Read More

Last updated: December 12, 2023. To get the first date and day of the month, first create a new instance of the native Date object and set its date to the first day of the month: const date = new Date(); // Creates new date object, default is current date date.setDate(1); // Sets date to first day of month (count starts from 1) date.toLocaleDateString(‘en-us’); // returns date e.g. 12/1/2023 You can then extract the day (as a number or string) and the date (in this case always 1) as follows: date.getDay(); // returns 0-6, where 0 = Sunday and 6…

Read More

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