📜  flash a button jquery onclick - Javascript(1)

📅  最后修改于: 2023-12-03 15:00:46.616000             🧑  作者: Mango

Flash a Button using jQuery onclick

Sometimes we want to add some animation to our webpage to make it more interactive and engaging. In this example, we will show how to flash a button using jQuery onclick.

HTML

We start by adding a simple button to our HTML, which will trigger the animation when clicked.

<button id="flashButton">Click me</button>
CSS

Next, we create a CSS class that will define the animation. In this case, we will make the button change its color to yellow and back to its original color repeatedly.

.flash {
  animation-name: flash;
  animation-duration: 0.5s;
  animation-iteration-count: infinite;
}

@keyframes flash {
  0% {
    background-color: white;
  }
  50% {
    background-color: yellow;
  }
  100% {
    background-color: white;
  }
}
jQuery

Finally, we use jQuery to add the onclick function to our button. When clicked, we add the 'flash' class to the button, which will trigger the animation.

$(document).ready(function() {
  $('#flashButton').click(function() {
    $(this).addClass('flash');
  });
});
Full HTML code
<!DOCTYPE html>
<html>
  <head>
    <style>
      .flash {
        animation-name: flash;
        animation-duration: 0.5s;
        animation-iteration-count: infinite;
      }

      @keyframes flash {
        0% {
          background-color: white;
        }
        50% {
          background-color: yellow;
        }
        100% {
          background-color: white;
        }
      }
    </style>
    <script
      src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
      integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+I6aD5g6qlU2zKRnas"
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <button id="flashButton">Click me</button>
    <script>
      $(document).ready(function() {
        $('#flashButton').click(function() {
          $(this).addClass('flash');
        });
      });
    </script>
  </body>
</html>
Conclusion

By following the steps above, you can add animation to your webpage and make it more interactive. Remember to always use CSS and jQuery responsibly and keep the user experience in mind.