search
HomeWeb Front-endCSS TutorialHow to Recreate the Ripple Effect of Material Design Buttons

How to Recreate the Ripple Effect of Material Design Buttons

When I first met Material Design, I was impressed by the design concept of its button components. It cleverly uses the ripple effect to provide feedback to users in a simple and elegant way.

How is this effect achieved? Material Design's buttons are not just simple ripples animations, but the position of the animation will also vary according to the position of the button clicked.

We can achieve the same effect through code. First, we will use ES6 JavaScript to provide a clean solution, and then explore some alternatives.

HTML structure

Our goal is to avoid any unnecessary HTML tags, so we will use the least code:

 <button>learn more</button>

Button style

We need to dynamically set some styles of the ripples element using JavaScript, but all other styles can be done in CSS. For our button, only two properties need to be included.

 button {
  position: relative;
  overflow: hidden;
}

Using position: relative allows us to use position: absolute on ripples elements, which is necessary for us to control its position. Meanwhile, overflow: hidden prevents ripples from exceeding the edge of the button. All other properties are optional. But now, our buttons look a little dated. Here is a more modern starting point:

 /* Roboto is the default font for Material*/
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');

button {
  position: relative;
  overflow: hidden;
  transition: background 400ms;
  color: #ffff;
  background-color: #6200ee;
  padding: 1rem 2rem;
  font-family: 'Roboto', sans-serif;
  font-size: 1.5rem;
  outline: 0;
  border: 0;
  border-radius: 0.25rem;
  box-shadow: 0 0 0.5rem rgba(0, 0, 0, 0.3);
  cursor: pointer;
}

Ripples style

Later, we will use JavaScript to use ripples as a .ripple class<span></span> Elements are injected into our HTML. But before moving to JavaScript, let's define the style of these ripples in CSS so we can use anytime:

 span.ripple {
  position: absolute; /* we mentioned above absolute positioning*/
  border-radius: 50%;
  transform: scale(0);
  animation: ripple 600ms linear;
  background-color: rgba(255, 255, 255, 0.7);
}

To make our ripples round, we set border-radius to 50%. To ensure that every ripples appear from scratch, we set the default scale to 0. Now, we can't see anything yet, because we haven't set values ​​for top , left , width , or height properties; we'll inject these properties soon using JavaScript.

As for our CSS, the last thing we need to add is the end state of the animation:

 @keyframes ripple {
  to {
    transform: scale(4);
    opacity: 0;
  }
}

Please note that we do not use from keyword to define the start state in keyframes ? We can omit from and CSS will build the missing value based on the value applied to the animation element. This happens if the relevant values ​​are explicitly declared (such as transform: scale(0) ), or they are default values ​​(such as opacity: 1 ).

JavaScript implementation

Finally, we need JavaScript to dynamically set the position and size of the ripples. The size should be based on the size of the button, and the position should be based on the position of the button and the cursor.

We will start with an empty function that takes the click event as an argument:

 function createRipple(event) {
  //
}

We will access our button by looking for currentTarget of the event.

 const button = event.currentTarget;

Next, we will instantiate ours<span></span> element and calculate its diameter and radius based on the width and height of the button.

 const circle = document.createElement("span");
const diameter = Math.max(button.clientWidth, button.clientHeight);
const radius = diameter / 2;

We can now define the remaining properties required by the ripples: left , top , width , and height .

 circle.style.width = circle.style.height = `${diameter}px`;
circle.style.left = `${event.clientX - (button.offsetLeft radius)}px`;
circle.style.top = `${event.clientY - (button.offsetTop radius)}px`;
circle.classList.add("ripple");

In<span></span> Before adding an element to the DOM, it is best to check if there are any remaining ripples that may have come from the previous click and delete them before executing the next ripples.

 const ripple = button.getElementsByClassName("ripple")[0];

if (ripple) {
  ripple.remove();
}

In the last step, we will<span></span> Append to the button element as a child element so that it is injected into the inside of the button.

 button.appendChild(circle);

After our function is finished, all that remains is to call it. This can be done in a number of ways. If we want to add ripples to each button on the page, we can use a code like this:

 const buttons = document.getElementsByTagName("button");
for (const button of buttons) {
  button.addEventListener("click", createRipple);
}

Now we have the ripple effect of working!

Extended features

What if we want to go a step further, combining this effect with other changes in button position or size? After all, customization is one of the main advantages of choosing to recreate the effects ourselves. To test the ease of the extension function, I decided to add a "magnet" effect that moves our button toward the cursor when it is within a specific area.

We need to rely on some of the same variables defined in the ripple function. To avoid unnecessary duplication of code, we should store them somewhere so that both methods can access them. But we should also limit the scope of shared variables to each individual button. One way to achieve this is to use a class as shown in the following example:

Since the magnet effect requires tracking the cursor every time the cursor moves, we no longer need to calculate the cursor position to create ripples. Instead, we can rely on cursorX and cursorY .

Two important new variables are magneticPullX and magneticPullY . They control the intensity of our magnet method pulling the button behind the cursor. So when we define the center of the ripples, we need to adjust the position (x and y) and the magnetism of the new button.

 const offsetLeft = this.left this.x * this.magneticPullX;
const offsetTop = this.top this.y * this.magneticPullY;

To apply these combination effects to all buttons, we need to instantiate a new class instance for each button:

 const buttons = document.getElementsByTagName("button");
for (const button of buttons) {
  new Button(button);
}

Other technologies

Of course, this is just one way to achieve the ripple effect. On CodePen, there are many examples that show different implementations. Here are some of my favorite examples.

Pure CSS implementation

If the user disables JavaScript, our Ripple Effect does not have any backup solution. However, using CSS only, using the :active pseudo-class to respond to clicks, you can get close to the original effect. The main limitation is that ripples can only appear from one point—usually the center of the button—and not in response to our click position. This example by Ben Szabo is particularly concise:

JavaScript before ES6

Leandro Parice's demo is similar to our implementation, but it is compatible with earlier versions of JavaScript:

jQuery

This example uses jQuery to achieve a ripple effect. If you already have jQuery as a dependency, it can help you save a few lines of code.

React

Finally, there is another example of me. While React's features such as state and refs can be used to help create ripple effects, this is not absolutely necessary. The position and size of the ripples need to be calculated for each click, so there is no advantage in keeping this information in the state. Additionally, we can access the button element from the click event, so we don't need refs either.

This React example uses the same createRipple function as the first implementation in this article. The main difference is that - as a method of Button component - our function is scoped to that component. Additionally, the onClick event listener is now part of our JSX:

This response maintains the original image formatting and avoids altering the core meaning of the text while rewarding phrases and sentences for a more natural flow and improved readability. It also uses more descriptive alt text for the images.

The above is the detailed content of How to Recreate the Ripple Effect of Material Design Buttons. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

What is CSS flexbox?What is CSS flexbox?Apr 30, 2025 pm 03:20 PM

Article discusses CSS Flexbox, a layout method for efficient alignment and distribution of space in responsive designs. It explains Flexbox usage, compares it with CSS Grid, and details browser support.

How can we make our website responsive using CSS?How can we make our website responsive using CSS?Apr 30, 2025 pm 03:19 PM

The article discusses techniques for creating responsive websites using CSS, including viewport meta tags, flexible grids, fluid media, media queries, and relative units. It also covers using CSS Grid and Flexbox together and recommends CSS framework

What does the CSS box-sizing property do?What does the CSS box-sizing property do?Apr 30, 2025 pm 03:18 PM

The article discusses the CSS box-sizing property, which controls how element dimensions are calculated. It explains values like content-box, border-box, and padding-box, and their impact on layout design and form alignment.

How can we animate using CSS?How can we animate using CSS?Apr 30, 2025 pm 03:17 PM

Article discusses creating animations using CSS, key properties, and combining with JavaScript. Main issue is browser compatibility.

Can we add 3D transformations to our project using CSS?Can we add 3D transformations to our project using CSS?Apr 30, 2025 pm 03:16 PM

Article discusses using CSS for 3D transformations, key properties, browser compatibility, and performance considerations for web projects.(Character count: 159)

How can we add gradients in CSS?How can we add gradients in CSS?Apr 30, 2025 pm 03:15 PM

The article discusses using CSS gradients (linear, radial, repeating) to enhance website visuals, adding depth, focus, and modern aesthetics.

What are pseudo-elements in CSS?What are pseudo-elements in CSS?Apr 30, 2025 pm 03:14 PM

Article discusses pseudo-elements in CSS, their use in enhancing HTML styling, and differences from pseudo-classes. Provides practical examples.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.