Menu class provides a way to create context menus and dropdown menus that can be displayed at specific positions or in response to mouse events.
Overview
Menus are commonly used for:- Right-click context menus
- Dropdown menus in custom UI elements
- Action menus with multiple options
- File/folder context menus
Constructor
Methods
addItem
Add a menu item to the menu.A callback function that receives a
MenuItem instance to configureReturns the menu instance for chaining
Example
addSeparator
Add a visual separator between menu items.Returns the menu instance for chaining
Example
showAtMouseEvent
Display the menu at the position of a mouse event.The mouse event to position the menu at (typically a right-click event)
Returns the menu instance for chaining
Example
showAtPosition
Display the menu at a specific position on screen.An object defining the position and display options for the menu
Optional document object (useful for popout windows)
Returns the menu instance for chaining
MenuPositionDef Properties
Horizontal position in pixels
Vertical position in pixels
Width of the menu in pixels
Whether the menu can overlap the target position
Whether to align the menu to the left
Example
hide
Hide the menu.Returns the menu instance for chaining
close
Close the menu (alias for hide).onHide
Register a callback to be called when the menu is hidden.Function to call when the menu is hidden
Example
setNoIcon
Prevent icons from being displayed in menu items.Returns the menu instance for chaining
setUseNativeMenu
Force the menu to use native or DOM rendering (desktop only).Whether to use native menu rendering
Returns the menu instance for chaining
Static Methods
forEvent
Create a menu for a pointer or mouse event (since 1.6.0).The event to create a menu for
A new Menu instance
MenuItem Class
Menu items are configured through theMenuItem class, which provides methods to customize their appearance and behavior.
setTitle
Set the title text of the menu item.The title text or DocumentFragment to display
setIcon
Set an icon for the menu item.The icon ID (from Lucide or custom icons), or null to remove the icon
setChecked
Set the checked state of the menu item.Whether the item should appear checked (true), unchecked (false), or neutral (null)
setDisabled
Disable or enable the menu item.Whether the item should be disabled
setWarning
Set the warning state (typically displays in red).Whether to enable the warning state
setIsLabel
Set whether the item is a label (non-clickable).Whether the item should be a label
onClick
Set the click handler for the menu item.Function to call when the item is clicked or activated via keyboard
setSection
Set the section this menu item belongs to.The section ID. Inspect DOM elements to find existing section IDs in Obsidian menus
Complete Example
See Also
- Workspace - Workspace events including file-menu
- Notice - For displaying notifications
- Button Component - For button icons