Confetti Animation in CSS on Button Click

Confetti Animation in CSS on Button Click
Code Snippet:Confetti Button
Author: Cooper Goeke
Published: January 21, 2024
Last Updated: January 22, 2024
Downloads: 3,972
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create an interactive button with a confetti animation. When you click the button, it goes through various stages: loading, completion, and a burst of colorful confetti and sequins. This code adds a fun and engaging visual effect to your website or application when users click the button.

The design of the button element improves user experience, increases user interaction, and is a fun way to acknowledge completed actions. You can use this code in websites, or interactive landing pages to enhance user engagement and create a playful interaction.

How to Create Confetti Animation In CSS On Button Click

1. First, load the Reset CSS by adding the following CDN link into the head tag of your HTML document. (Optional)

  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">

2. Create the HTML structure for your button and canvas where the confetti animation will be displayed. Place the following code in your HTML file:

  1. <button id="button" class="ready" onclick="clickButton();">
  2. <div class="message submitMessage">
  3. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 12.2">
  4. <polyline stroke="currentColor" points="2,7.1 6.5,11.1 11,7.1 "/>
  5. <line stroke="currentColor" x1="6.5" y1="1.2" x2="6.5" y2="10.3"/>
  6. </svg> <span class="button-text">Submit</span>
  7. </div>
  8. <div class="message loadingMessage">
  9. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19 17">
  10. <circle class="loadingCircle" cx="2.2" cy="10" r="1.6"/>
  11. <circle class="loadingCircle" cx="9.5" cy="10" r="1.6"/>
  12. <circle class="loadingCircle" cx="16.8" cy="10" r="1.6"/>
  13. </svg>
  14. </div>
  15. <div class="message successMessage">
  16. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 11">
  17. <polyline stroke="currentColor" points="1.4,5.8 5.1,9.5 11.6,2.1 "/>
  18. </svg> <span class="button-text">Success</span>
  19. </div>
  20. </button>
  21. <canvas id="canvas"></canvas>

3. Include the CSS styles to define the appearance and behavior of your button and confetti animation. You can customize the styles to match your website’s design. Here’s a snippet of the CSS code:

  1. @keyframes loading {
  2. 0% {
  3. cy: 10;
  4. }
  5. 25% {
  6. cy: 3;
  7. }
  8. 50% {
  9. cy: 10;
  10. }
  11. }
  12. body {
  13. -webkit-font-smoothing: antialiased;
  14. background-color: #f4f7ff;
  15. }
  16.  
  17. canvas {
  18. width: 640px !important;
  19. height: 220px !important;
  20. position: absolute;
  21. top: 0;
  22. pointer-events: none;
  23. margin: auto;
  24. z-index: 2;
  25. }
  26.  
  27. button {
  28. display: block;
  29. background: none;
  30. border: none;
  31. color: #f4f7ff;
  32. cursor: pointer;
  33. font-family: "Quicksand", sans-serif;
  34. font-size: 14px;
  35. font-weight: 500;
  36. height: 40px;
  37. outline: none;
  38. position: relative;
  39. overflow: hidden;
  40. padding: 0 10px;
  41. width: 190px;
  42. -webkit-tap-highlight-color: transparent;
  43. z-index: 1;
  44. margin: 20px auto;
  45. }
  46. button::before {
  47. background: #1f2335;
  48. border-radius: 50px;
  49. box-shadow: 0 2px 5px rgba(0, 0, 0, 0.4) inset;
  50. content: "";
  51. display: block;
  52. height: 100%;
  53. margin: 0 auto;
  54. position: relative;
  55. transition: width 0.2s cubic-bezier(0.39, 1.86, 0.64, 1) 0.3s;
  56. width: 100%;
  57. }
  58.  
  59. button.ready .submitMessage svg {
  60. opacity: 1;
  61. top: 1px;
  62. transition: top 0.4s ease 600ms, opacity 0.3s linear 600ms;
  63. }
  64. button.ready .submitMessage .button-text span {
  65. top: 0;
  66. opacity: 1;
  67. transition: all 0.2s ease calc(var(--dr) + 600ms);
  68. }
  69.  
  70. button.loading::before {
  71. transition: width 0.3s ease;
  72. width: 80%;
  73. }
  74. button.loading .loadingMessage {
  75. opacity: 1;
  76. }
  77. button.loading .loadingCircle {
  78. animation-duration: 1s;
  79. animation-iteration-count: infinite;
  80. animation-name: loading;
  81. cy: 10;
  82. }
  83.  
  84. button.complete .submitMessage svg {
  85. top: -30px;
  86. transition: none;
  87. }
  88. button.complete .submitMessage .button-text span {
  89. top: -8px;
  90. transition: none;
  91. }
  92. button.complete .loadingMessage {
  93. top: 80px;
  94. }
  95. button.complete .successMessage .button-text span {
  96. left: 0;
  97. opacity: 1;
  98. transition: all 0.2s ease calc(var(--d) + 1000ms);
  99. }
  100. button.complete .successMessage svg {
  101. stroke-dashoffset: 0;
  102. transition: stroke-dashoffset 0.3s ease-in-out 1.4s;
  103. }
  104.  
  105. .button-text span {
  106. opacity: 0;
  107. position: relative;
  108. }
  109.  
  110. .message {
  111. left: 50%;
  112. position: absolute;
  113. top: 50%;
  114. transform: translate(-50%, -50%);
  115. width: 100%;
  116. }
  117.  
  118. .message svg {
  119. display: inline-block;
  120. fill: none;
  121. margin-right: 5px;
  122. stroke-linecap: round;
  123. stroke-linejoin: round;
  124. stroke-width: 2;
  125. }
  126.  
  127. .submitMessage .button-text span {
  128. top: 8px;
  129. transition: all 0.2s ease var(--d);
  130. }
  131. .submitMessage svg {
  132. color: #5c86ff;
  133. margin-left: -1px;
  134. opacity: 0;
  135. position: relative;
  136. top: 30px;
  137. transition: top 0.4s ease, opacity 0.3s linear;
  138. width: 14px;
  139. }
  140.  
  141. .loadingMessage {
  142. opacity: 0;
  143. transition: opacity 0.3s linear 0.3s, top 0.4s cubic-bezier(0.22, 0, 0.41, -0.57);
  144. }
  145. .loadingMessage svg {
  146. fill: #5c86ff;
  147. margin: 0;
  148. width: 22px;
  149. }
  150.  
  151. .successMessage .button-text span {
  152. left: 5px;
  153. transition: all 0.2s ease var(--dr);
  154. }
  155. .successMessage svg {
  156. color: #5cffa1;
  157. stroke-dasharray: 20;
  158. stroke-dashoffset: 20;
  159. transition: stroke-dashoffset 0.3s ease-in-out;
  160. width: 14px;
  161. }
  162.  
  163. .loadingCircle:nth-child(2) {
  164. animation-delay: 0.1s;
  165. }
  166.  
  167. .loadingCircle:nth-child(3) {
  168. animation-delay: 0.2s;
  169. }
  170.  
  171. /* Website Link */
  172. .website-link {
  173. background: #f8faff;
  174. border-radius: 50px 0 0 50px;
  175. bottom: 30px;
  176. color: #324b77;
  177. cursor: pointer;
  178. font-family: "Montserrat", sans-serif;
  179. font-weight: 600;
  180. height: 34px;
  181. filter: drop-shadow(2px 3px 4px rgba(0, 0, 0, 0.1));
  182. padding: 0 20px 0 40px;
  183. position: fixed;
  184. right: 0;
  185. text-align: left;
  186. text-decoration: none;
  187. }
  188. .website-link__icon {
  189. left: -10px;
  190. position: absolute;
  191. top: -12px;
  192. width: 44px;
  193. }
  194. .website-link__name {
  195. display: block;
  196. font-size: 14px;
  197. line-height: 14px;
  198. margin: 5px 0 3px;
  199. }
  200. .website-link__last-name {
  201. color: #55bada;
  202. }
  203. .website-link__message {
  204. color: #8aa8c5;
  205. display: block;
  206. font-size: 7px;
  207. line-height: 7px;
  208. }

4. Use JavaScript to handle button clicks and trigger the confetti animation. You’ll need to initialize the confetti and sequin objects, as well as define their physics and behavior. Insert the JavaScript code into your HTML file:

  1. // ammount to add on each button press
  2. const confettiCount = 20
  3. const sequinCount = 10
  4.  
  5. // "physics" variables
  6. const gravityConfetti = 0.3
  7. const gravitySequins = 0.55
  8. const dragConfetti = 0.075
  9. const dragSequins = 0.02
  10. const terminalVelocity = 3
  11.  
  12. // init other global elements
  13. const button = document.getElementById('button')
  14. var disabled = false
  15. const canvas = document.getElementById('canvas')
  16. const ctx = canvas.getContext('2d')
  17. canvas.width = window.innerWidth
  18. canvas.height = window.innerHeight
  19. let cx = ctx.canvas.width / 2
  20. let cy = ctx.canvas.height / 2
  21.  
  22. // add Confetto/Sequin objects to arrays to draw them
  23. let confetti = []
  24. let sequins = []
  25.  
  26. // colors, back side is darker for confetti flipping
  27. const colors = [
  28. { front : '#7b5cff', back: '#6245e0' }, // Purple
  29. { front : '#b3c7ff', back: '#8fa5e5' }, // Light Blue
  30. { front : '#5c86ff', back: '#345dd1' } // Darker Blue
  31. ]
  32.  
  33. // helper function to pick a random number within a range
  34. randomRange = (min, max) => Math.random() * (max - min) + min
  35.  
  36. // helper function to get initial velocities for confetti
  37. // this weighted spread helps the confetti look more realistic
  38. initConfettoVelocity = (xRange, yRange) => {
  39. const x = randomRange(xRange[0], xRange[1])
  40. const range = yRange[1] - yRange[0] + 1
  41. let y = yRange[1] - Math.abs(randomRange(0, range) + randomRange(0, range) - range)
  42. if (y >= yRange[1] - 1) {
  43. // Occasional confetto goes higher than the max
  44. y += (Math.random() < .25) ? randomRange(1, 3) : 0
  45. }
  46. return {x: x, y: -y}
  47. }
  48.  
  49. // Confetto Class
  50. function Confetto() {
  51. this.randomModifier = randomRange(0, 99)
  52. this.color = colors[Math.floor(randomRange(0, colors.length))]
  53. this.dimensions = {
  54. x: randomRange(5, 9),
  55. y: randomRange(8, 15),
  56. }
  57. this.position = {
  58. x: randomRange(canvas.width/2 - button.offsetWidth/4, canvas.width/2 + button.offsetWidth/4),
  59. y: randomRange(canvas.height/2 + button.offsetHeight/2 + 8, canvas.height/2 + (1.5 * button.offsetHeight) - 8),
  60. }
  61. this.rotation = randomRange(0, 2 * Math.PI)
  62. this.scale = {
  63. x: 1,
  64. y: 1,
  65. }
  66. this.velocity = initConfettoVelocity([-9, 9], [6, 11])
  67. }
  68. Confetto.prototype.update = function() {
  69. // apply forces to velocity
  70. this.velocity.x -= this.velocity.x * dragConfetti
  71. this.velocity.y = Math.min(this.velocity.y + gravityConfetti, terminalVelocity)
  72. this.velocity.x += Math.random() > 0.5 ? Math.random() : -Math.random()
  73. // set position
  74. this.position.x += this.velocity.x
  75. this.position.y += this.velocity.y
  76.  
  77. // spin confetto by scaling y and set the color, .09 just slows cosine frequency
  78. this.scale.y = Math.cos((this.position.y + this.randomModifier) * 0.09)
  79. }
  80.  
  81. // Sequin Class
  82. function Sequin() {
  83. this.color = colors[Math.floor(randomRange(0, colors.length))].back,
  84. this.radius = randomRange(1, 2),
  85. this.position = {
  86. x: randomRange(canvas.width/2 - button.offsetWidth/3, canvas.width/2 + button.offsetWidth/3),
  87. y: randomRange(canvas.height/2 + button.offsetHeight/2 + 8, canvas.height/2 + (1.5 * button.offsetHeight) - 8),
  88. },
  89. this.velocity = {
  90. x: randomRange(-6, 6),
  91. y: randomRange(-8, -12)
  92. }
  93. }
  94. Sequin.prototype.update = function() {
  95. // apply forces to velocity
  96. this.velocity.x -= this.velocity.x * dragSequins
  97. this.velocity.y = this.velocity.y + gravitySequins
  98. // set position
  99. this.position.x += this.velocity.x
  100. this.position.y += this.velocity.y
  101. }
  102.  
  103. // add elements to arrays to be drawn
  104. initBurst = () => {
  105. for (let i = 0; i < confettiCount; i++) {
  106. confetti.push(new Confetto())
  107. }
  108. for (let i = 0; i < sequinCount; i++) {
  109. sequins.push(new Sequin())
  110. }
  111. }
  112.  
  113. // draws the elements on the canvas
  114. render = () => {
  115. ctx.clearRect(0, 0, canvas.width, canvas.height)
  116. confetti.forEach((confetto, index) => {
  117. let width = (confetto.dimensions.x * confetto.scale.x)
  118. let height = (confetto.dimensions.y * confetto.scale.y)
  119. // move canvas to position and rotate
  120. ctx.translate(confetto.position.x, confetto.position.y)
  121. ctx.rotate(confetto.rotation)
  122.  
  123. // update confetto "physics" values
  124. confetto.update()
  125. // get front or back fill color
  126. ctx.fillStyle = confetto.scale.y > 0 ? confetto.color.front : confetto.color.back
  127. // draw confetto
  128. ctx.fillRect(-width / 2, -height / 2, width, height)
  129. // reset transform matrix
  130. ctx.setTransform(1, 0, 0, 1, 0, 0)
  131.  
  132. // clear rectangle where button cuts off
  133. if (confetto.velocity.y < 0) {
  134. ctx.clearRect(canvas.width/2 - button.offsetWidth/2, canvas.height/2 + button.offsetHeight/2, button.offsetWidth, button.offsetHeight)
  135. }
  136. })
  137.  
  138. sequins.forEach((sequin, index) => {
  139. // move canvas to position
  140. ctx.translate(sequin.position.x, sequin.position.y)
  141. // update sequin "physics" values
  142. sequin.update()
  143. // set the color
  144. ctx.fillStyle = sequin.color
  145. // draw sequin
  146. ctx.beginPath()
  147. ctx.arc(0, 0, sequin.radius, 0, 2 * Math.PI)
  148. ctx.fill()
  149.  
  150. // reset transform matrix
  151. ctx.setTransform(1, 0, 0, 1, 0, 0)
  152.  
  153. // clear rectangle where button cuts off
  154. if (sequin.velocity.y < 0) {
  155. ctx.clearRect(canvas.width/2 - button.offsetWidth/2, canvas.height/2 + button.offsetHeight/2, button.offsetWidth, button.offsetHeight)
  156. }
  157. })
  158.  
  159. // remove confetti and sequins that fall off the screen
  160. // must be done in seperate loops to avoid noticeable flickering
  161. confetti.forEach((confetto, index) => {
  162. if (confetto.position.y >= canvas.height) confetti.splice(index, 1)
  163. })
  164. sequins.forEach((sequin, index) => {
  165. if (sequin.position.y >= canvas.height) sequins.splice(index, 1)
  166. })
  167.  
  168. window.requestAnimationFrame(render)
  169. }
  170.  
  171. // cycle through button states when clicked
  172. clickButton = () => {
  173. if (!disabled) {
  174. disabled = true
  175. // Loading stage
  176. button.classList.add('loading')
  177. button.classList.remove('ready')
  178. setTimeout(() => {
  179. // Completed stage
  180. button.classList.add('complete')
  181. button.classList.remove('loading')
  182. setTimeout(() => {
  183. window.initBurst()
  184. setTimeout(() => {
  185. // Reset button so user can select it again
  186. disabled = false
  187. button.classList.add('ready')
  188. button.classList.remove('complete')
  189. }, 4000)
  190. }, 320)
  191. }, 1800)
  192. }
  193. }
  194.  
  195. // re-init canvas if the window size changes
  196. resizeCanvas = () => {
  197. canvas.width = window.innerWidth
  198. canvas.height = window.innerHeight
  199. cx = ctx.canvas.width / 2
  200. cy = ctx.canvas.height / 2
  201. }
  202.  
  203. // resize listenter
  204. window.addEventListener('resize', () => {
  205. resizeCanvas()
  206. })
  207.  
  208. // click button on spacebar or return keypress
  209. document.body.onkeyup = (e) => {
  210. if (e.keyCode == 13 || e.keyCode == 32) {
  211. clickButton()
  212. }
  213. }
  214.  
  215. // Set up button text transition timings on page load
  216. textElements = button.querySelectorAll('.button-text')
  217. textElements.forEach((element) => {
  218. characters = element.innerText.split('')
  219. let characterHTML = ''
  220. characters.forEach((letter, index) => {
  221. characterHTML += `<span class="char${index}" style="--d:${index * 30}ms; --dr:${(characters.length - index - 1) * 30}ms;">${letter}</span>`
  222. })
  223. element.innerHTML = characterHTML
  224. })
  225.  
  226. // kick off the render loop
  227. window.initBurst()
  228. render()

That’s all! hopefully, you have successfully created a Confetti Animation in CSS on Button Click. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X