Magento2 creating and calling modal widget
You should create a module first, then after create a requirejs-config.js
file at app/code/Vendor/YourModule/view/frontend/requirejs-config.js
var config = {
paths: {
'myjs': "Vendor_YourModule/js/myfile"
},
shim: {
'myjs': {
deps: ['jquery']
}
}
}
You need to create myfile.js
in app/code/Vendor/YourModule/view/frontend/web/js/myfile.js
require(
[
'jquery',
'Magento_Ui/js/modal/modal'
],
function(
$,
modal
) {
var options = {
type: 'popup',
responsive: true,
innerScroll: true,
buttons: [{
text: $.mage.__('Continue'),
class: 'mymodal1',
click: function () {
this.closeModal();
}
}]
};
var popup = modal(options, $('#popup-modal'));
$("#click-me").on('click',function(){
$("#popup-modal").modal("openModal");
});
}
);
Then your phtml file should look like:
<div data-mage-init='{"myjs": {}}'>
<a href="#" id="click-me">Click Me</a>
</div>
<div id="popup-modal" >
yes I am the modal.
</div>
You just need to add a container for the modal <div id="popup-modal"></div>
and a small bit of javascript to initialise the modal like below:
<div id="popup-modal"><p>Hello World</p></div>
<script>
require(
[
'jquery',
'Magento_Ui/js/modal/modal'
],
function(
$,
modal
) {
let options = {
type: 'popup',
responsive: true,
innerScroll: true,
title: 'Modal Title',
modalClass: 'custom-modal',
buttons: [{
text: $.mage.__('Continue'),
class: '',
click: function () {
this.closeModal();
}
}]
};
let $myModal = $('#popup-modal');
let popup = modal(options, $myModal);
//this opens the modal, you can use some click event or whatever you need to trigger the modal here
$myModal.modal('openModal');
}
);
</script>
So the $myModal.modal('openModal');
will trigger the popup instantly however could be used like below to maybe trigger when clicking a button or link for example:
$(".open-modal").click(function() {
$myModal.modal('openModal');
});
I have used this, hope this will help you
<button type="button" class="action" data-trigger="trigger">
<span data-bind="i18n: 'Click Here'"></span>
</button>
<div data-bind="mageInit: {
'Magento_Ui/js/modal/modal':{
'type': 'popup',
'title': 'Popup title',
'trigger': '[data-trigger=trigger]',
'responsive': true,
'buttons': [{
text: 'Submit',
class: 'action'
}]
}}">
<div class="content">
Popup Content
</div>
</div>