One of the things that I miss in Magento 2 is being able to automatically hide information messages on any page of the online store. Modifying behavior is not excessively difficult, but you have to have clear a couple of things about how the Magento 2 eCommerce messaging system works.

In Magento 2, Knockout is used to render messages through an observable, so messages can be displayed dynamically using ajax without reloading the page by adding them with the MessageFactory.

In order to add a timeout to the block of messages, we need to modify the observable to handle the state of said block (hidden or not). The best option is to create a small module to manage these changes, using a mixin and modifying the template by layout. For this Magento 2 tutorial, however, we will do it in a more rough-and-ready way, so as not to get lost in the details of the module.

How to automatically hide messages in Magento 2

Overwriting the message block

As we are going to make an overwrite, we copy the file 

vendor/magento/module-theme/view/frontend/templates/messages.phtml en app/design/frontend/vendor/theme/Magento_Theme/templates/messages.phtml


The difference from the base file is the following line:

data-bind="visible: isVisible(), click: removeAll

With this, we can control if the message should be hidden and, if visible, hidden when the message is clicked. We will manage this behavior from the JS component.

Overwriting of the JS component

As with the phtml we copy the file:

vendor/magento/module-theme/view/frontend/web/js/view/messages.js en app/design/frontend/vendor/theme/Magento_Theme/web/js/view/messages.js.

The resulting code is the following:


Notice that we have modified the attributes of the component (two added) and also the functions initObservable, isVisible, removeAll and onHiddenChange.

We’ve added an isHidden parameter is added, and a “listens”, which calls the  onHiddenChange function. This is the function that is responsible for launching the timeout and hiding the message using jQuery.

You can see this behavior in the checkout messages, which use a different message component than the entire store. With these changes, the behaviors are unified.

Interactiv4 is more than an ecommerce agency; we are your ecommerce partner and Magento 2 specialists for local and global growth. Best-in-class technology, proven expertise, commitment to your success… and so much passion for ecommerce.