Skip to content

Commit

Permalink
Close dialog on click 'outside'
Browse files Browse the repository at this point in the history
When clicking outside the dialog (on the backdrop) we call the `closeDialog` function. As it is not possible to add event listeners for pseudo-element we rely on the fact that the dialog element is target only when the backdrop is clicked.
  • Loading branch information
alex-ju committed Oct 13, 2022
1 parent 70281b4 commit 0a9387d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/components/addon/components/hds/dialog/index.hbs
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
<dialog class={{this.classNames}} ...attributes aria-labelledby={{this.id}} {{did-insert this.setupDialog}}>
{{! template-lint-disable no-invalid-interactive }}
<dialog
class={{this.classNames}}
...attributes
aria-labelledby={{this.id}}
{{on "click" this.onClick}}
{{did-insert this.setupDialog}}
>
{{yield (hash Header=(component "hds/dialog/header" id=this.id closeDialog=this.closeDialog))}}
{{yield (hash Body=(component "hds/dialog/body"))}}
{{yield (hash Footer=(component "hds/dialog/footer"))}}
Expand Down
9 changes: 9 additions & 0 deletions packages/components/addon/components/hds/dialog/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ export default class HdsDialogIndexComponent extends Component {
element.showModal();
}

@action
onClick(event) {
// This may seem counterintuitive, but the <dialog> element is the target only when the backdrop is clicked
// otherwise the target would be a child of the <dialog>
if (event.target.tagName === 'DIALOG') {
this.closeDialog();
}
}

@action
closeDialog() {
this.element.close();
Expand Down

0 comments on commit 0a9387d

Please sign in to comment.