How to hide success messages after 5 seconds in Magento 2? I want to hide this message shown in the below picture after 5 seconds. it is coming from message.phtml file.
2 Answers
- Create app/code/Rakesh/MagentoStackExchange/view/frontend/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_Theme/js/view/messages': {
'Rakesh_MagentoStackExchange/js/view/messages-mixin': true
}
}
}
};
- Create app/code/Rakesh/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.
-
yes its working but i just want to run setTimout function only on mobile screen. screen with less than 800. how can i modify it? Commented Oct 10, 2019 at 5:54
-
@JunaidAshfaq may be you need to add this condition
if(screen.width < 800) { setTimeout(function() { customerData.set('messages', {}); }, 5000); //disappear the message in 5 seconds }
Commented Oct 10, 2019 at 5:59 -
yes its working i have added (screen.width < 800) in condition thanks Commented Oct 10, 2019 at 6:42
-
-
Do i need <sequence> <module name="Magento_Theme"/> </sequence> in module.xml Commented Feb 17, 2020 at 10:02
You can do it by overriding the Magento's messages-mixin.js
in your custom module.
view/frontend/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_Theme/js/view/messages': {
'Vendor_Module/js/view/messages-mixin': true
}
}
}
};
view/frontend/web/js/view/messages-mixin.js
define([
'Magento_Customer/js/customer-data'
], function (customerData) {
'use strict';
return function (target) {
return target.extend({
initialize: function () {
this._super();
var self = this;
self.messages.subscribe(function(messages) {
if (messages.messages) {
if (messages.messages.length > 0) {
if (window.screen.width < 800) {
setTimeout(function() {
customerData.set('messages', {});
}, 5000); //disappear the message in 5 seconds
}
}
}
});
}
});
}
});
Run the below commands after the changes:
php bin/magento c:f
Hope it helps!!!
-
yes its working but i just want to run setTimout function only on mobile screen. screen with less than 800. how can i modify it? Commented Oct 10, 2019 at 5:55
-
-
1yes its working i have added (screen.width < 800) in condition thanks Commented Oct 10, 2019 at 6:41
-
Hi @Sumit this is not working for me I created a new module and i followed your steps but not working Commented Feb 17, 2020 at 9:59
-
Do i need <sequence> <module name="Magento_Theme"/> </sequence> in module.xml Commented Feb 17, 2020 at 10:01