Magento – Hide messages after certain interval

knockoutjsmagento-2.1messages

How to hide notification messages like success message after adding product to cart or any error messages or notices after few seconds after they appear on the the frontend using knockout js.

Example : When I am adding a product in the cart, a success message appear saying "product has been added to your cart". I want to hide this success message after 5 seconds after it appear on the screen.

Best Answer

Try following way:

Vendor/Module/view/frontend/requirejs-config.js

var config = {
    "map": {
        "*": {
            "Magento_Theme/js/view/messages": "Vendor_Module/js/view/messages",
        }
    }
}

Vendor/Module/view/frontend/web/js/view/messages.js

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

    return Component.extend({
        defaults: {
            cookieMessages: [],
            messages: []
        },

        /** @inheritdoc */
        initialize: function () {
            this._super();

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

            if (!_.isEmpty(this.messages().messages)) {
                customerData.set('messages', {});
            }

            $.cookieStorage.set('mage-messages', '');
            setTimeout(function() {
                $(".messages").hide('blind', {}, 500)
            }, 5000);
        }
    });
});

Clear cache.

Related Topic