Hide custom error messages after a certain time in Magento 2

Create a new message Js file in your module or you can also override directly by adding the same file in your theme directory.

define([
    'jquery',
    'uiComponent',
    'Magento_Customer/js/customer-data',
    'underscore',
    'escaper',
    'jquery/jquery-storageapi'
], function ($, Component, customerData, _, escaper) {
    'use strict';

    return Component.extend({
        defaults: {
            cookieMessages: [],
            messages: [],
            allowedTags: ['div', 'span', 'b', 'strong', 'i', 'em', 'u', 'a']
        },

        /**
         * Extends Component object by storage observable messages.
         */
        initialize: function () {
            this._super();

            this.cookieMessages = _.unique($.cookieStorage.get('mage-messages'), 'text');
            this.messages = customerData.get('messages').extend({
                disposableCustomerData: 'messages'
            });

            // Force to clean obsolete messages
            if (!_.isEmpty(this.messages().messages)) {
                customerData.set('messages', {});
            }

            $.cookieStorage.set('mage-messages', '');
            
        },

        /**
         * Prepare the given message to be rendered as HTML
         *
         * @param {String} message
         * @return {String}
         */
        prepareMessageForHtml: function (message) {
            $(".messages").show();
            setTimeout(function() {
                $(".messages").hide('blind', {}, 500)
            }, 5000);
            return escaper.escapeHtml(message, this.allowedTags);
        }
        
    });
});
After run this command php bin/magento setup:upgrade && php bin/magento setup:static-content:deploy -f

Leave a comment

Your email address will not be published. Required fields are marked *