Magento 2 – How to Hide Messages After Certain Time

javascriptmagento2messages

I want to hide success / error messages after 5 seconds once I have added items to the cart.

I have extended messages.js with the following code to hide the message after 5 seconds

setTimeout(function() {
    $(".messages").hide('blind', {}, 500);
}, 3000); 

When I add item to the cart for the first time the message gets hidden after 5 seconds but when I add another item to the cart the message is not showing up.

Best Answer

  1. Create app/code/SR/MagentoStackExchange/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Theme/js/view/messages': {
                'SR_MagentoStackExchange/js/view/messages-mixin': true
            }
        }
    }
};
  1. Create app/code/SR/MagentoStackExchange/view/frontend/web/js/view/messages-mixin.js

define([
    'Magento_Customer/js/customer-data'
], function (customerData) {
    'use strict';

    return function (target) {
        return target.extend({
            /**
             * Extends Component object by storage observable messages.
             */
            initialize: function () {
                this._super();
                var self = this;
                self.messages.subscribe(function(messages) {
                    if (messages.messages) {
                        if (messages.messages.length > 0) {
                            setTimeout(function() {
                                customerData.set('messages', {});
                            }, 3000);
                        }
                    }
                });
            }
        });
    }
});

Clear browser js cache.

Note: I have tested in 2.3 version.

Related Topic