Prevent focus to previous element in EJ2 JavaScript Dialog control

30 Aug 20254 minutes to read

By default, when the dialog is closed, focus returns to the element that was previously focused before the dialog opened. You can prevent this behavior using the beforeClose event and setting the preventFocus argument to true.

Bind the beforeClose event and enable the preventFocus argument as shown in the sample below.

// Initialize the Dialog component using Syncfusion's Dialog class
var dialogObj = new ej.popups.Dialog({
    header: 'Delete Multiple Items',
    content: "Are you sure you want to permanently delete all of these items?",
    showCloseIcon: true,
    buttons: [
        { 
            buttonModel: { isPrimary: true, content: 'Yes' }, 
            click: btnClick
        },
        { 
            buttonModel: { content: 'No' }, 
            click: btnClick
        }
    ],
    // Specifies the target element where the dialog will be rendered
    target: document.body,
    height: 'auto',
    width: '300px',
    animationSettings: { effect: 'Zoom' },

    // Event triggered before the dialog closes
    beforeClose: function (args) {
        // Prevents the dialog from regaining focus after closing
        args.preventFocus = true;
    }
});

// Append the dialog to the DOM element with ID 'dialog'
dialogObj.appendTo('#dialog');
document.getElementById('openBtn').onclick = function () {
    dialogObj.show(); 
};

function btnClick() {
    dialogObj.hide(); 
}
<!DOCTYPE html><html lang="en"><head>
    <title>Essential JS 2 Dialog with header</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="TypeScript UI Components">
    <meta name="author" content="Syncfusion">
    <link href="styles.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/31.1.17/ej2-base/styles/material.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/31.1.17/ej2-buttons/styles/material.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/31.1.17/ej2-inputs/styles/material.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/31.1.17/ej2-popups/styles/material.css" rel="stylesheet">
    
    
<script src="https://cdn.syncfusion.com/ej2/31.1.17/dist/ej2.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    
    <div id="container">
        <button id="openBtn" class="e-control e-btn">Open</button>
        <div id="dialog"> </div>
    </div>

<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
      </script>
<script src="index.js" type="text/javascript"></script>
</body></html>