[Java] [Rails] Fade out flash message with javascript without using jquery

1 minute read

Introduction

I’m developing a Rails app and want to make flash messages fade out, so I wrote it because I implemented it using javascript.

These guys ↓ ↓ (we have applied Bootstrap’s alert) Screenshots 2020-07-04 8.59.20.png

Fade this out

Environment

Ruby: 2.5.1 Rails: 5.2.4.2

Implementation

As an implementation image, gradually increase the transparency and finally hide it.

Element’s style attribute ① Decrease the value of opacity ② When opacity becomes 0, set display: none;

view file

erb looks like this

_flash_messages.html.erb


<% flash.each do |message_type, message| %>
  <div class="alert alert-<%= message_type %>"><%= message %></div>
<% end %>

js file

flash_message.js


// run on page load with turbolinks:load
document.addEventListener('turbolinks:load', () => {

  // Get the flash message element
  const flashMessage = document.querySelector('.alert');

  // Define a function that fades out (transparently, hides)
  const fadeOutFlashMessage = () => {
    // Store the return value in the variable timer_id to identify setInterval
    const timer_id = setInterval(() => {
      // Get style attribute opacity of flash message
      const opacity = flashMessage.style.opacity;

      if (opacity >0) {
      // Decrease 0.02 if opacity is greater than 0
        flashMessage.style.opacity = opacity-0.02;
      } else {
        // Hide when the opacity value reaches 0
        flashMessage.style.display ='none';
        // stop setInterval
        clearInterval(timer_id);
      };
    }, 50); // This time execute setInterval every 0.05 seconds
  }

  // Only run if there is a flash message
  if (flashMessage !== null) {
    // set style attribute opacity
    flashMessage.style.opacity = 1;
    // This time, after 3 seconds from display, execute the function to fade out defined above
    setTimeout(fadeOutFlashMessage, 3000);
  };
});

References

I have referred to the following article. Thank you very much.

Turolinks cheat sheet[JavaScript] How to fade out Rails flash and erase it

Finally

Thank you for reading. I would be very pleased if you could point out any mistakes or more efficient description methods.