简体   繁体   中英

I get undefined error using pure javascript in my code

I am trying to add a material ripple effect to an element using pure javascript using the code below. The problem is that the effect works only for the first click. If I try to click the button again, I get the message Uncaught TypeError: circle is undefined on my console.

 function createRipple(event) { const target = event.currentTarget; const circle = target.classList.add("ripple"); const ripple = circle.getElementsByClassName("ripple")[0]; if (ripple) { ripple.remove(); } } const buttons = document.getElementsByClassName("my-ripple"); for (const button of buttons) { button.addEventListener("click", createRipple); }
 .my-ripple { position: relative; overflow: hidden; display: inline-block; width: auto; padding: 1.2rem; font-family: sans; cursor: pointer; border-radius: 10px; }.ripple::after { content: ""; position: absolute; border-radius: 50%; transform: scale(0); animation: ripple 600ms linear; background-color: rgba(0, 0, 0, 0.5); top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: 100px; height: 100px; } @keyframes ripple { to { transform: scale(4); opacity: 0; } }
 <div class="my-ripple">Click me</div>

classList does not return an object. And you do not need it actually, because you already have the target instance, so fetching it again by class is not necessary. Instead just remove the class from it directly with a timeout:

function createRipple(event) {
  const target = event.currentTarget;
  target.classList.add("ripple");
  setTimeout(function() {
    target.classList.remove("ripple");
  }, 600);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM