Skip to main content

Overview

The Modal class creates a modal dialog that overlays the main application window. Modals are useful for displaying temporary content, forms, or prompts that require user attention.

Constructor

app
App
required
Reference to the Obsidian App instance
const modal = new Modal(this.app);

Properties

app
App
Reference to the App instance
scope
Scope
Keyboard scope for the modal, used for handling hotkeys
containerEl
HTMLElement
The outer container element of the modal
modalEl
HTMLElement
The main modal element
titleEl
HTMLElement
Element containing the modal title
contentEl
HTMLElement
Element containing the modal content. Add your custom content here.
shouldRestoreSelection
boolean
Whether to restore the previous text selection when the modal closes. Default is true.Since: 0.9.16

Methods

open()

Shows the modal on the active window. On mobile devices, the modal will animate onto the screen.
modal.open();

close()

Hides and closes the modal.
modal.close();

onOpen()

Override this method to perform setup when the modal is opened. This is where you should add content to contentEl.
class ExampleModal extends Modal {
  onOpen() {
    const { contentEl } = this;
    contentEl.setText('Hello, World!');
  }
}
Returns: Promise<void> | void

onClose()

Override this method to perform cleanup when the modal is closed.
class ExampleModal extends Modal {
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
}

setTitle()

Sets the title of the modal.
title
string
required
The title text to display
modal.setTitle('My Modal Title');
Returns: this (for chaining)

setContent()

Sets the content of the modal.
content
string | DocumentFragment
required
The content to display, either as a string or DocumentFragment
modal.setContent('This is the modal content.');
Returns: this (for chaining)

setCloseCallback()

Registers a callback to be called when the modal closes.
callback
() => any
required
Function to execute when the modal closes
modal.setCloseCallback(() => {
  console.log('Modal closed');
});
Returns: this (for chaining) Since: 1.10.0

Example

import { Modal, App } from 'obsidian';

class ExampleModal extends Modal {
  constructor(app: App) {
    super(app);
  }

  onOpen() {
    const { contentEl } = this;
    contentEl.createEl('h1', { text: 'Welcome!' });
    contentEl.createEl('p', { text: 'This is a custom modal.' });
    
    const button = contentEl.createEl('button', { text: 'Close' });
    button.addEventListener('click', () => {
      this.close();
    });
  }

  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
}

// Usage
const modal = new ExampleModal(this.app);
modal.open();

See Also

Build docs developers (and LLMs) love