[Rails] Fade out flash messages with javascript without using jquery

Introduction

I'm developing a Rails app and want to fade out flash messages, so I implemented it using javascript, so I'll write it.

These guys ↓ ↓ (Bootstrap alert is applied) スクリーンショット 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 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


// turbolinks:Execute when loading page with load
document.addEventListener('turbolinks:load', () => {

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

  //Fade out (gradually transparent,Define a function (to hide)
  const fadeOutFlashMessage = () => {
    //Variable timer as the return value to specify setInterval_Store in id
    const timer_id = setInterval(() => {
      //Get style attribute opacity of flash message
      const opacity = flashMessage.style.opacity;

      if (opacity > 0) {
      //0 if the opacity value is greater than 0.Decrease the value by 02
        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 0.Execute setInterval every 05 seconds
  }

  //Run only if there is a flash message
  if (flashMessage !== null) {
    //set style attribute opacity
    flashMessage.style.opacity = 1;
    //This time, execute the function that fades out as defined above 3 seconds after the display.
    setTimeout(fadeOutFlashMessage, 3000);
  };
});

References

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

Cheat sheet -[JavaScript] How to fade out Rails flash and erase it

Finally

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

Recommended Posts

[Rails] Fade out flash messages with javascript without using jquery
Fade out Rails flash without moving other content
Timeless search with Rails + JavaScript (jQuery)
Japaneseize using i18n with Rails
[Rails] How to use flash messages
Notes on using FCM with Ruby on Rails