Functions That Attach to DOM Elements
Element Modifiers
Modifiers run on DOM elements — perfect for imperative work like focus, scroll, drag, or wiring up third-party libraries.
What you'll learn
- Install ember-modifier
- Write a function-based modifier
- Manage lifecycle and cleanup
Modifiers are reusable functions that attach to elements in templates — the right place to put imperative DOM work in Octane.
Install
ember install ember-modifier Function Modifier
// app/modifiers/focus-on-insert.js
import { modifier } from 'ember-modifier';
export default modifier(function focusOnInsert(element) {
element.focus();
}); <input {{focus-on-insert}} /> The first argument is the element. The second is positional args, the third is named args.
With Args and Cleanup
The modifier can return a cleanup function — Ember calls it when the element is destroyed or the args change.
import { modifier } from 'ember-modifier';
export default modifier(function clickOutside(element, [handler]) {
function onDoc(e) {
if (!element.contains(e.target)) handler(e);
}
document.addEventListener('click', onDoc);
return () => document.removeEventListener('click', onDoc);
}); <div {{click-outside this.close}}>...</div> Class-Based Modifiers
For lifecycle hooks (modify, willDestroy) and service injection, extend
class Modifier:
import Modifier from 'ember-modifier';
import { service } from '@ember/service';
export default class TrackVisible extends Modifier {
@service analytics;
modify(element, [name]) {
this.analytics.track('visible', name);
}
}