7 Key Influencer Marketing Trends in 2024

Featured Imgs 23

Influencer marketing is one of the most powerful and most effective forms of digital marketing available today.

With a market value of over $21 billion dollars, over 3X the value since 2019, influencer marketing continues to grow as it provides a level playing field for both big and small brands to compete for the user’s attention.

According to a survey by Matter Communications, 81% of people claimed they’ve made purchases based on recommendations from influencers, friends, and family.

Unlike other traditional forms of marketing, influencer marketing evolves with new trends, strategies, and concepts. Each year, you’ll see something new and different that brings better results for your campaigns.

In this post, we take a deep dive into some of these newest influencer marketing trends to see how you can leverage them to get better returns on investment (ROI). These methods might not be as effective next year so it’s better to take advantage of them right now!

1. Rise of AI Influencers

It’s no secret that most influencers on social media platforms now utilize some form of AI in their content creation process to make everything look perfect, whether it’s writing better captions, generating AI images, or even enhancing their everyday photos with a little bit of AI editing.

However, real influencers will have to do much more than that to stay relevant as they now have new competition from an entirely new group of influencers that are even more seemingly perfect.

ai influencer instagram

Miquela is just one of many AI influencers currently taking over social media platforms. With more than 2.5 million followers, this AI influencer is not even the biggest account of its kind.

While it’s a new concept, most of these AI influencer accounts are already creating sponsored content and brands do not hesitate to get their products reviewed by an AI personality.

The same trend can be seen across all social media platforms from VTubers on YouTube to AI models on Instagram and TikTok. Facebook is also working on a new AI personality model that allows creators to make AI representations of themselves.

At this rapid rate of advancements in AI, it’s difficult to predict how big of an impact it will have on social media.

2. TikTok Domination

60-second videos are still the “king” of social media marketing and TikTok is still in the lead on that front. Especially when it comes to targeting Gen-Z audiences, TikTok is the go-to platform for marketing campaigns.

statista social media platforms

(Source: Statista)

Even though TikTok ranks at the 5th position in terms of the number of monthly active users, it is the most popular platform among brands for influencer marketing. 66% of brands use TikTok for their influencer marketing campaigns, with only 47% using Instagram, 33% YouTube, and 28% Facebook.

Even though Instagram, YouTube, and Facebook have also implemented their own versions of short-form content formats, TikTok still dominates the Gen-Z market with its trend-making content creation system.

3. Growth of Nano-Influencers

Gone are the days of looking up to celebrities for fashion and lifestyle advice. Now, younger audiences, especially Gen-Zers, turn to smaller influencers for fashion advice.

According to another study by Matter Communications, 60% to 70% of consumers prefer advice from small influencers who are experts in their field while only 17% to 22% listen to popular celebrities.

micro influencers tiktok

(Source: TikTok)

In fact, the smaller the follower count the better. Engagement rates were much higher for influencers with 1,000 to 10,000 followers (nano-influencers) than influencers with 10,000 to 50,000 followers (micro-influencers).

The biggest reason for this is authenticity. Smaller influencers put more effort and energy into creating more original content and having closer relationships with their audience.

4. Niche Trends vs Global Trends

Going viral on a social media platform is still a shot in the dark. With changing algorithms and audience interests, no one can predict what the next meme or trending hashtag could be. While big brands are still making bets on these global trends, smaller brands and businesses are now slowly turning towards niche trends.

google trends local trending

(Source: Google Trends)

Local and niche trends are much easier to target than taking a shot at a trending global hashtag or an event. Small brands have a much higher chance of going viral on a small scale with niche trends, making it easier to even target specific local audiences.

Working with small, local influencers is the key to success in niche trends. Finding micro and nano influencers who specialize in a niche market will make it much easier to target your ideal audience and create trendy content that goes viral.

5. Long-term Campaigns

Influencer marketing is a marathon, not a sprint. You can’t convince your target audience to buy your product over a more established, competing product with just a single TikTok video. It takes long-term campaigns and partnerships to achieve that goal.

This is why many businesses now set aside marketing budgets specifically for content and influencer marketing. According to a HubSpot report, 50% of marketers plan on increasing their content marketing budgets this year.

long term partnerships youtube

(Source: YouTube)

As a result, most brands are now establishing long-term partnerships with influencers. Some even go as far as making ambassador-like partnerships that allows influencers to promote products exclusively from a single brand.

It’s an effective way to win over an audience rather than one-time sponsorships from an influencer who promotes products from different brands without consistency.

6. Livestream Shopping & User-Generated Content (UGC)

Leveraging user-generated content (UGC) in social media marketing is nothing new. It’s been an effective strategy for many years. However, a new trend in UGC offers a more effective, multi-layered approach that brings much higher benefits.

It involves partnering with influencers to encourage their audience to create content about a product. Usually, a giveaway or some sort of a prize is necessary for this process, sometimes even asking the audience to involve their friends as a part of the process.

This type of marketing greatly benefits the brand as it generates buzz around the product and the brand on multiple levels.

whatnot

Livestream shopping plays a huge role in this process as well. Platforms like Whatnot are allowing content creators and influencers to easily create shopping experiences and involve their audiences in the process.

7. Influencer Seeding

Sending influencers free product samples, also known as influencer seeding, is still an effective strategy used in social media marketing. While it’s not as engaging as sponsored partnerships, this strategy allows much smaller businesses without big marketing budgets to create a presence for their brand.

Influencer Seeding

(Source: TikTok)

A better way to approach this method is to create personalized packages that show the influencers how much you appreciate them and what they are doing. Including several additional free product samples for a giveaway will also get their attention.

Conclusion

As you can see, there are many different opportunities and ways to approach influencer marketing. Big or small, every brand can use these influencer trends to create awareness and reach new audiences. Be on the lookout for the latest trends and leverage them to beat the competition.

Press This: WordPress as a Design Tool—Empowering Users to Create

Featured Imgs 23

Welcome to Press This, a podcast that delivers valuable insights and actionable tips for navigating the ever-evolving world of WordPress.  In this episode, host Brian Gardner and Automattic Product Lead Rich Tabor, unpack WordPress’s design potential, highlighting its evolving features and the power it offers website builders. Powered by RedCircle Brian Gardner: Hey everybody, welcome

The post Press This: WordPress as a Design Tool—Empowering Users to Create appeared first on WP Engine.

Introducing

Category Image 076

I created a little library at work to make those “skeleton screens” that I’m not sure anyone likes. […] We named it skellyCSS because… skeletons and CSS, I guess. We still aren’t even really using it very much, but it was fun to do and it was the first node package I made myself (for the most part).

Regardless of whether or not anyone “likes” skeleton screens, they do come up and have their use cases. And they’re probably not something you want to rebuild time and again. Great use for a web component, I’d say! Maybe Ryan can get Uncle Dave to add it to his Awesome Standalones list. 😉

The other reason I’m sharing this link is that Ryan draws attention to the Web Components De-Mystified course that Scott Jehl recently published, something worth checking out of course, but that I needed a reminder for myself.


Introducing <shelly-wc> originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.



from CSS-Tricks https://ift.tt/yMOhIXK
Gain $200 in a week
via Read more

Useful Tools for Creating AVIF Images

Category Image 076

AVIF (AV1 Image File Format) is a modern image file format specification for storing images that offer a much more significant file reduction when compared to other formats like JPG, JPEG, PNG, and WebP. Version 1.0.0 of the AVIF specification was finalized in February 2019 and released by Alliance for Open Media to the public.

You save 50% of your file size when compared to JPG and 20% compared to WebP while still maintaining the image quality.

In this article, you will learn about some browser-based tools and command-line tools for creating AVIF images.

Why use AVIF over JPGs, PNGS, WebP, and GIF?

  • Lossless compression and lossy compression
  • JPEG suffers from awful banding
  • WebP is much better, but there’s still noticeable blockiness compared to the AVIF
  • Multiple color space
  • 8, 10, 12-bit color depth

Caveats

Jake Archibald, wrote an article a few years back on this new image format and also helped us to identify some disadvantages to compressing images, normally you should look out for these two when compressing to AVIF:

  1. If a user looks at the image in the context of the page, and it strikes them as ugly due to compression, then that level of compression is not acceptable. But, one tiny notch above that boundary is fine.
  2. It’s okay for the image to lose noticeable detail compared to the original unless that detail is significant to the context of the image.

See also: Addy Osmani at Smashing Magazine goes in-depth on using AVIF and WebP.

Data on support for the avif feature across the major browsers from caniuse.com

Browser Solutions

Squoosh

Screenshot of Squoosh.
Screenshot of Squoosh.

Squoosh is a popular image compression web app that allows you to convert images in numerous formats to other widely used compressed formats, including AVIF.

Features
  • File-size limit: 4MB
  • Image optimization settings (located on the right side)
  • Download controls – this includes seeing the size of the resulting file and the percentage reduction from the original image
  • Free to use

Cloudinary

Cloudinary’s free image-to-AVIF converter is another image tool that doesn’t require any form of code. All you need to do is upload your selected images (PNG, JPG, GIF, etc.) and it returns compressed versions of them. Its API even has more features besides creating AVIF images like its image enhancement and artificially generating filling for images.

I’m pretty sure you’re here because you’re looking for a free and fast converter. So, the browser solution should do.

Features

  • No stated file size limit
  • Free to use

You can find answers to common questions in the Cloudinary AVIF converter FAQ.

Command Line Solutions

avif-cli

avif-cli by lovell lets you take your images (PNG, JPEG, etc.) stored in a folder and converts them to AVIF images of your specified reduction size.

Here are the requirements and what you need to do:

  • Node.js 12.13.0+

Install the package:

npm install avif

Run the command in your terminal:

npx avif --input="./imgs/*" --output="./output/" --verbose
  • ./imgs/* – represents the location of all your image files
  • ./output/ – represents the location of your output folder
Features
  • Free to use
  • Speed of conversion can be set

You can find out about more commands via the avif-cli GitHub page.

sharp

sharp is another useful tool for converting large images in common formats to smaller, web-friendly AVIF images.

Here are the requirements and what you need to do:

  • Node.js 12.13.0+

Install the package:

npm install sharp

Create a JavaScript file named sharp-example.js and copy this code:

const sharp = require('sharp')

const convertToAVIF = () => {
    sharp('path_to_image')
    .toFormat('avif', {palette: true})
    .toFile(__dirname + 'path_to_output_image')
}

convertToAVIF()

Where path_to_image represents the path to your image with its name and extension, i.e.:

./imgs/example.jpg

And path_to_output_image represents the path you want your image to be stored with its name and new extension, i.e.:

/sharp-compressed/compressed-example.avif

Run the command in your terminal:

node sharp-example.js

And there! You should have a compressed AVIF file in your output location!

Features
  • Free to use
  • Images can be rotated, blurred, resized, cropped, scaled, and more using sharp

See also: Stanley Ulili’s article on How To Process Images in Node.js With Sharp.

Conclusion

AVIF is a technology that front-end developers should consider for their projects. These tools allow you to convert your existing JPEG and PNG images to AVIF format. But as with adopting any new tool in your workflow, the benefits and downsides will need to be properly evaluated in accordance with your particular use case.

I hope you enjoyed reading this article as much as I enjoyed writing it. Thank you so much for your time and I hope you have a great day ahead!


Useful Tools for Creating AVIF Images originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.



from CSS-Tricks https://ift.tt/bLlHG8x
Gain $200 in a week
via Read more

The “Other” C in CSS

Category Image 052

I think it’s worth listening to anything Sara Soueidan has to say. That’s especially true if she’s speaking at an event for the first time in four years, which was the case when she took the stage at CSS Day 2024 in Amsterdam. What I enjoy most about Sara is how she not only explains the why behind everything she presents but offers it in a way that makes me go “a-ha!” instead of “oh crap, I’m doing everything wrong.”

(Oh, and you should take her course on Practical Accessibility.)

Sara’s presentation, “The Other ‘C’ in CSS”, was published on YouTube just last week. It’s roughly 55 minutes of must-see points on the various ways CSS can, and does, impact accessibility. I began watching the presentation casually but quickly fired up a place where I could take thorough notes once I found myself ooo-ing and ahhh-ing along.

So, these are the things I took away from Sara’s presentation. Let me know if you’ve also taken notes so we can compare! Here we go, there’s a lot to take in.

Here’s the video

Yes, CSS affects accessibility

CSS changes more than the visual appearance of elements, whether we like it or not. More than that, its effects cascade down to HTML and the accessibility tree (accTree). And when we’re talking about the accTree, we’re referring to a list of objects that describes and defines accessible information about elements.

There are typically four main bits of info about an accTree object:

  • Role: what kind of thing is this? Most HTML elements map to ARIA roles, but not all of them.
  • Name: identifies the element in the user interface.
  • Description: how do we further describe the thing?
  • State: what is its current state? Announce it!

The browser provides interactive features — like checking a checkbox that updates and exposes the element’s information — so the user knows what happens following an interaction.

Accessibility tree objects may also contain properties and relationships, such as whether it is part of a group or labeled by another element.

Example: List semantics

CSS can affect an object’s accessible role, name, description, or even whether it is exposed in the accTree at all. As such, it can directly impact the screen reader announcement. We shared a while back how removing list-style affects list semantics, particularly in the case of Safari, and Sara explains its nuances.

/* Removes list role semantics in Safari */
/* Need to add aria-role=list */
ul {
  list-style: none;
}

/* Does not remove role semantics in Safari */
nav ul {
  list-style: none:
}

/* Removed unless specifically re-added in the markup */
ul:where([role="list"]) {
  list-style: none;
}

/* Preserves list semantics */
ul {
  list-style: "";
}

display: contents

CSS can completely remove the presence of an element from the accessibility tree. I took a screenshot from one of Sara’s slides but it’s just so darn helpful that I figured putting the info in a table would be more useful:

Exposed to a11y APIs?Keyboard accessible?Visually accessible (rendered)?Children exposed to a11y APIs?
display: none
visibility: hidden
opactity: 0 and filter: opacity(0)
clip-path: inset(100%)
position(off-canvas)
.visually-hidden
display: contents

The display: contents method does more than it’s supposed to. In short, we know that display controls the type of box an element generates. A value of none, for example, generates no box.

The contents value is sort of like none in that not box is generated. The difference is that it has no impact on the element’s children. In other words, declaring contents does not remove the element or its child elements from the accTree. More than that, there’s a current bug report saying that declaring contents in Firefox breaks the anchoring effect of an ID attribute attached to an element.

Eric Bailey says that using display: contents is considered harmful. If using it, the recommendation is to set it on a generic <div> instead of a semantically meaningful element. If we were to use it on a meaningful interactive element, it would be removed from the accTree, and its children would be bumped up to the next level in the DOM.

Visually hiding stuff

Many, many of us use some sort of .visibility-hidden class as a utility for hiding elements while allowing screenreaders to pick them up and announce the contents. TPGi has a great breakdown of the technique.

.visually-hidden:not(:focus):not(:active) {
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0 0 0 0); /* for IE only */
  clip-path: inset(50%);
  position: absolute;
  white-space: nowrap;
}

This is super close to what I personally use in my work, but the two :not() statements were new to me and threw me for a loop. What they do is make sure that the selector only applies when the element is neither focused nor activated.

It’s easy to slap this class on things we want to hide and call it a day. But we have to be careful and use it intentionally when the situation allows for us to hide but still announce an element. For example, we would not want to use this on interactive elements because those should be displayed at all times. If you’re interacting with something, we have to be able to see it. But for generic text stuff, all good. Skip to content links, too.

There’s an exception! We may want an animated checkbox and have to hide the native control’s appearance so that it remains hidden, even though CSS is styling it in a way that it is visible. We still have to account for the form control’s different states and how it is announced to assistive tech. For example, if we hide the native checkbox for a custom one by positioning it way off the screen, the assistive tech will not announce it on focus or activation. Better to absolutely position the checkbox over the custom one to get the interactive accessibility benefits.

Bottom line: Ask yourself whether an interactive element will become visible when it receives focus when deciding whether or not to use a .visually-hidden utility.

CSS and accessible names

The browser follows a specific process when it determines an element’s accessible name (accName):

  • First, it checks for aria-labelledby. If present, and if the ID in the attribute is a valid reference to an element on the page, it uses the reference’s element’s computed text as the element’s accessible name.
  • Otherwise, it checks for aria-label.
  • Otherwise, unless the element is marked with role="presentation" or role="none" (i.e., the element does not accept an accName anymore), the browser checks if the element can get its own name, which could happen in a few ways, including:
    • from an HTML elemnenty, such as alt or title (which is best on an <iframe>; otherwise, avoid),
    • from another element, like <label> or <legend>, or
    • from its contents.

At this point, Sara went into a brief (but wonderful) tangent on <button> semantics. Buttons are labelable elements and can get their accName by using an aria-label attribute, an aria-labelledby attribute, its contents, or even a <label> element.

ARIA takes precedence over HTML which is why we want to avoid it only where we have to. We can see the priorities and overrides for accessible names in DevTools under the Accessibility tab when inspecting elements.

DevTools exposing the accessibility tree of the document and aria attributes for a selected anchor element.

But note: the order of priority defined in the accName computation algorithm does not define the order of priority that you should follow when providing an accName to elements. The steps should like be reversed if anything. Prioritize native HTML!

CSS generated content

Avoid using CSS to create meaningful content. Here’s why:

<a href="#" class="info">CSS generated content</a>
.info::before {
  content: "ⓘ" / "Info: ";
  /* or */
  content: url('path-to-icon.svg') / "Info: ";
}

/* Contents: : Info: CSS generated content. */

But it’s more nuanced than that. For one, we’re unable to translate content generated by CSS into different languages, at least via automated tools. Another one: that content is gone if CSS is unavailable for whatever reason. I didn’t think this would ever be too big a concern until Sara reminded me that some contexts completely strip out CSS, like Safari’s Reader Mode (something I rely on practically every day, but wish I didn’t have to).

There are also edge cases where CSS generated content might be inaccessible, including in Forced Colors environments (read: color conflicts), or if a broken image is passed to the url() function (read: alt text of the image is not shown in place of the broken image, at least in most browsers, yet it still contributes to the accName, violating SC 2.5.3 Label in Name). Adrian Roselli’s article on the topic includes comprehensive test results of the new feature, showing different results.

Inline SVG is probably better! But we can also do this to help with icons that are meant to be decorative to not repeat redundant information. But it is inconsistent as far as browser implementation (but Sara says Safari gets it right).

/* like: <img src="icon.svg" alt=""> */
.icon {
  content: url('path/to/icon.svg') / "";
}

So, what can we do to help prevent awkward and inaccessible situations that use CSS generated content?

  • Avoid using CSS pseudo-elements for meaningful content — use HTML!
  • Hide decorative and redundant CSS content by giving it an empty alt text (when support is there and behavior is consistent).

CSS can completely strip an element of its accName…

…if the source of the name is hidden in a way that removes it from the accessibility tree.

For example, an <input> can get its accName from a <label>, but that label is hidden by CSS in a way that doesn’t expose it to a11y APIs. In other words, the <label> is no longer rendered and neither are its contents, so the input winds up with no accName.

Showing the HTML for a label-input pair and CSS that uses display: none to hide the label.

BUT! Per spec:

By default assistive technologies do not relay hidden information, but an author can explicitly override that and include hidden text as part of the accessible name or accessible description by using aria-labelledby or aria-describedby.

So, in this case, we can reuse the label even if it is hidden by tacking on aria-labelledby. We could use the .visually-hidden utility, but the label is still accessible and will continue to be announced.

Using aria-labelled by on an text form input with DevTools showing the input's accessible name which is pulled from the label element.

CSS does not affect the state of an element in the accTree

If we use a <button> to show/hide another element, for example, the <button> element state needs to expose that state. Content on hover or focus violates SC 1.4.13 which requires a way to dismiss the content. And users must be able to move their cursor away from the text and have it persist.

CSS-only modals using the checkbox hack are terrible because they don’t trap focus, don’t make the page content inert, and don’t manage keyboard focus (without JavaScript).

Popovers created with the Popover API are always non-modal. If you want to create a modal popover, a <dialog> is the right way to go. I’m enamored with Jhey Tompkins’s demo using the popover for a flyout navigation component, so much so that I used it in another article. But, using popover for modal-type stuff — including for something like a flyout nav — we still need to update the accessible states.

There’s much more to consider, from focus traps to inert content. But we can also consider removing the popover’s ::backdrop for fewer restrictions, like making background content inert or trapping focus. Then again, something like a popover-based flyout navigation violates SC 2.4.12 Focus Not Obscured if it covers or obscures another element with focus. So, yes, visibility is important for usability but we should shoot for better usability that goes beyond WCAG conformance. (Sara elaborates on this in a comment down below.)

So… close the popover when focus leaves it. Sara mentioned an article that Amit Sheen wrote for Smashing Magazine where it’d be wise to pay close attention to how a change is communicated to the user when a <select> menu <option> is selected to update colors on the page. That poses issues about SC 3.2.2 where something changes on input. When the user interacts with it, the user should know what’s going to happen.

Final thoughts

Yeah, let all that sink in. It feels good, right? Again, what I love most about Sara’s presentation (or any of them, for that matter) is that she isn’t pointing any condemning fingers at anyone. I care about oodles accessible experiences but know just how much I don’t know, and it’s practical stuff like this where I see clear connections to my work that can make me better.

I took one more note from Sara’s talk and didn’t quite know where to put it, but I think the conclusion makes sense because it’s a solid reminder that HTML, CSS, and, yes JavaScript, all have seats at the table and can each contribute positively to accessible experience:

  • Hacking around JavaScript with CSS can introduce accessible barriers. JavasScript is still useful and required for these things. Use the right tool for the job.

The “Other” C in CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Crafted With Code: Performance Showcase

Featured Imgs 23

This year’s Crafted With Code showcase has already highlighted five projects recognized by the Webby Awards and WP Engine, each featuring beautifully designed, highly accessible digital experiences.  Now, Crafted With Code is shining a light on some of the most performant projects submitted to the Webbys this year. The Webby Awards exist to honor excellence

The post Crafted With Code: Performance Showcase appeared first on WP Engine.

Understanding Gutenberg Blocks, Patterns, and Templates

Category Image 091

Developers suffer in the great multitudes whom their sacred block-based websites cannot reach.

Johannes Gutenberg (probably)

Long time WordPresser, first time Gutenberger here. I’m a fan even though I’m still anchored to a classic/block hybrid setup. I believe Johanes himself would be, too, trading feather pens for blocks. He was a forward-thinking 15th-century inventor, after all.

My enthusiasm for Gutenberg-ness is curbed at the theming level. I’ll sling blocks all day long in the Block Editor, but please, oh please, let me keep my classic PHP templates and the Template Hierarchy that comes with it. The separation between theming and editing is one I cherish. It’s not that the Site Editor and its full-site editing capabilities scare me. It’s more that I fail to see the architectural connection between the Site and Block Editors. There’s a connection for sure, so the failure of not understanding it is more on me than WordPress.

The WP Minute published a guide that clearly — and succinctly — describes the relationships between WordPress blocks, patterns, and templates. There are plenty of other places that do the same, but this guide is organized nicely in that it starts with the blocks as the lowest-level common denominator, then builds on top of it to show how patterns are comprised of blocks used for content layout, synced patterns are the same but are one of many that are edited together, and templates are full page layouts cobbled from different patterns and a sprinkle of other “theme blocks” that are the equivalent of global components in a design system, say a main nav or a post loop.

The guide outlines it much better, of course:

  1. Gutenberg Blocks: The smallest unit of content
  2. Patterns: Collections of blocks for reuse across your site
  3. Synced Patterns: Creating “master patterns” for site-wide updates
  4. Synced Pattern Overrides: Locking patterns while allowing specific edits
  5. Templates: The structural framework of your WordPress site

That “overrides” enhancement to the synced patterns feature is new to me. I’m familiar with synced patterns (with a giant nod to Ganesh Dahal) but must’ve missed that in the WordPress 6.6 release earlier this summer.

I’m not sure when or if I’ll ever go with a truly modern WordPress full-site editing setup wholesale, out-of-the-box. I don’t feel pressured to, and I believe WordPress doesn’t care one way or another. WordPress’s ultimate selling point has always been its flexibility (driven, of course, by the massive and supportive open-source community behind it). It’s still the “right” tool for many types of projects and likely will remain so as long as it maintains its support for classic, block, and hybrid architectures.


Understanding Gutenberg Blocks, Patterns, and Templates originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Generating Unique Random Numbers In JavaScript Using Sets

Category Image 080

JavaScript comes with a lot of built-in functions that allow you to carry out so many different operations. One of these built-in functions is the Math.random() method, which generates a random floating-point number that can then be manipulated into integers.

However, if you wish to generate a series of unique random numbers and create more random effects in your code, you will need to come up with a custom solution for yourself because the Math.random() method on its own cannot do that for you.

In this article, we’re going to be learning how to circumvent this issue and generate a series of unique random numbers using the Set object in JavaScript, which we can then use to create more randomized effects in our code.

Note: This article assumes that you know how to generate random numbers in JavaScript, as well as how to work with sets and arrays.

Generating a Unique Series of Random Numbers

One of the ways to generate a unique series of random numbers in JavaScript is by using Set objects. The reason why we’re making use of sets is because the elements of a set are unique. We can iteratively generate and insert random integers into sets until we get the number of integers we want.

And since sets do not allow duplicate elements, they are going to serve as a filter to remove all of the duplicate numbers that are generated and inserted into them so that we get a set of unique integers.

Here’s how we are going to approach the work:

  1. Create a Set object.
  2. Define how many random numbers to produce and what range of numbers to use.
  3. Generate each random number and immediately insert the numbers into the Set until the Set is filled with a certain number of them.

The following is a quick example of how the code comes together:

function generateRandomNumbers(count, min, max) {
  // 1: Create a Set object
  let uniqueNumbers = new Set();
  while (uniqueNumbers.size < count) {
    // 2: Generate each random number
    uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);
  }
  // 3: Immediately insert them numbers into the Set...
  return Array.from(uniqueNumbers);
}
// ...set how many numbers to generate from a given range
console.log(generateRandomNumbers(5, 5, 10));

What the code does is create a new Set object and then generate and add the random numbers to the set until our desired number of integers has been included in the set. The reason why we’re returning an array is because they are easier to work with.

One thing to note, however, is that the number of integers you want to generate (represented by count in the code) should be less than the upper limit of your range plus one (represented by max + 1 in the code). Otherwise, the code will run forever. You can add an if statement to the code to ensure that this is always the case:

function generateRandomNumbers(count, min, max) {
  // if statement checks that count is less than max + 1
  if (count > max + 1) {
    return "count cannot be greater than the upper limit of range";
  } else {
    let uniqueNumbers = new Set();
    while (uniqueNumbers.size < count) {
      uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);
    }
    return Array.from(uniqueNumbers);
  }
}
console.log(generateRandomNumbers(5, 5, 10));
Using the Series of Unique Random Numbers as Array Indexes

It is one thing to generate a series of random numbers. It’s another thing to use them.

Being able to use a series of random numbers with arrays unlocks so many possibilities: you can use them in shuffling playlists in a music app, randomly sampling data for analysis, or, as I did, shuffling the tiles in a memory game.

Let’s take the code from the last example and work off of it to return random letters of the alphabet. First, we’ll construct an array of letters:

const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];

// rest of code

Then we map the letters in the range of numbers:

const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];

// generateRandomNumbers()

const randomAlphabets = randomIndexes.map((index) => englishAlphabets[index]);

In the original code, the generateRandomNumbers() function is logged to the console. This time, we’ll construct a new variable that calls the function so it can be consumed by randomAlphabets:

const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];

// generateRandomNumbers()

const randomIndexes = generateRandomNumbers(5, 0, 25);
const randomAlphabets = randomIndexes.map((index) => englishAlphabets[index]);

Now we can log the output to the console like we did before to see the results:

const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];

// generateRandomNumbers()

const randomIndexes = generateRandomNumbers(5, 0, 25);
const randomAlphabets = randomIndexes.map((index) => englishAlphabets[index]);
console.log(randomAlphabets);

And, when we put the generateRandomNumbers`()` function definition back in, we get the final code:

const englishAlphabets = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];
function generateRandomNumbers(count, min, max) {
  if (count > max + 1) {
    return "count cannot be greater than the upper limit of range";
  } else {
    let uniqueNumbers = new Set();
    while (uniqueNumbers.size < count) {
      uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);
    }
    return Array.from(uniqueNumbers);
  }
}
const randomIndexes = generateRandomNumbers(5, 0, 25);
const randomAlphabets = randomIndexes.map((index) => englishAlphabets[index]);
console.log(randomAlphabets);

So, in this example, we created a new array of alphabets by randomly selecting some letters in our englishAlphabets array.

You can pass in a count argument of englishAlphabets.length to the generateRandomNumbers function if you desire to shuffle the elements in the englishAlphabets array instead. This is what I mean:

generateRandomNumbers(englishAlphabets.length, 0, 25);
Wrapping Up

In this article, we’ve discussed how to create randomization in JavaScript by covering how to generate a series of unique random numbers, how to use these random numbers as indexes for arrays, and also some practical applications of randomization.

The best way to learn anything in software development is by consuming content and reinforcing whatever knowledge you’ve gotten from that content by practicing. So, don’t stop here. Run the examples in this tutorial (if you haven’t done so), play around with them, come up with your own unique solutions, and also don’t forget to share your good work. Ciao!

Basic keyboard shortcut support for focused links

Category Image 076

Eric gifting us with his research on all the various things that anchors (not links) do when they are in :focus.

Turns out, there’s a lot!

That’s an understatement! This is an incredible amount of work, even if Eric calls it “dry as a toast sandwich.” Boring ain’t always a bad thing. Let me simply drop in a pen that Dave put together pulling all of Eric’s findings into a table organized to compare the different behaviors between operating systems — and additional tables for each specific platform — because I think it helps frame Eric’s points.

That really is a lot! But why on Earth go through the trouble of documenting all of this?

All of the previously documented behavior needs to be built in JavaScript, since we need to go the synthetic link route. It also means that it is code we need to set aside time and resources to maintain.

That also assumes that is even possible to recreate every expected feature in JavaScript, which is not true. It also leaves out the mental gymnastics required to make a business case for prioritizing engineering efforts to re-make each feature.

There’s the rub! These are the behaviors you’re gonna need to mimic and maintain if veering away from semantic, native web elements. So what Eric is generously providing is perhaps an ultimate argument against adopting frameworks — or rolling some custom system — that purposely abstract the accessible parts of the web, often in favor of DX.

As with anything, there’s more than meets the eye to all this. Eric’s got an exhaustive list at the end there that calls out all the various limitations of his research. Most of those notes sound to me like there are many, many other platforms, edge cases, user agent variations, assistive technologies, and considerations that could also be taken into account, meaning we could be responsible for a much longer list of behaviors than what’s already there.

And yes, this sweatshirt is incredible. Indeed.


Basic keyboard shortcut support for focused links originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.



from CSS-Tricks https://ift.tt/YLyXexn
Gain $200 in a week
via Read more

Introducing Sandbox Sites on WP Engine

Featured Imgs 23

The wonderful thing about hosting more of the top 200,000 WordPress sites and watching site-building workflows evolve over a fourteen-year history is that you start to see patterns.  Patterns emerge in support queries, customer conversations, and developer behavior, and at WP Engine, these patterns have informed innovations like multi-dev environments, bulk site-management features, our Headless WordPress

The post Introducing Sandbox Sites on WP Engine appeared first on WP Engine.

Callbacks on Web Components?

Category Image 076

A gem from Chris Ferdinandi that details how to use custom events to hook into Web Components. More importantly, Chris dutifully explains why custom events are a better fit than, say, callback functions.

With a typical JavaScript library, you pass callbacks in as part of the instantiate process. […] Because Web Components self-instantiate, though, there’s no easy way to do that.

There’s a way to use callback functions, just not an “easy” way to go about it.

JavaScript provides developers with a way to emit custom events that developers can listen for with the Element.addEventListener() method.

We can use custom events to let developers hook into the code that we write and run more code in response to when things happen. They provide a really flexible way to extend the functionality of a library or code base.

Don’t miss the nugget about canceling custom events!


Callbacks on Web Components? originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.



from CSS-Tricks https://ift.tt/whICV5D
Gain $200 in a week
via Read more