Best practicesGlobal CSS
While the shadow DOM is disabled (as is default),
CSS styles can be applied globally instead of within the element's css hook.
It's recommended to place all non-dynamic styles within a global CSS file to limit the CSS rules applied
when the element updates, and marginally improve performance.
/* styles.css */
custom-element {
font-size: 18px;
margin: 24px;
}
custom-element > div {
padding: 6px;
}
Or, if you're using SCSS:
/* styles.scss */
custom-element {
font-size: 18px;
margin: 24px;
& > div {
padding: 6px;
}
}
// custom-element.js
modjool.create({
tag: 'custom-element',
html: ({ slot }) => `
<div>${slot}</div>
`,
// Applying dynamic styles
css: ({ attr }) => `
div {
color: ${attr.textColor || 'black'};
}
`
})
While the shadow DOM is enabled, it's recommended to place all styles within the css hook.
Default data values
In more complex elements, it's recommended to set default values in the data hook,
to split up the logic and the templates.
// ❌ Messy
html: ({ attr, data }) => `
<div title="${attr.name || 'Default name'}" class="${attr.shadow ? 'shadow' : ''}">
<h1>${attr.name || 'Default name'}</h1>
<p>Welcome ${attr.name || 'Default name'}. ${attr.message || 'Enjoy your stay!'}</p>
</div>
`// ✅ Tidy
data: ({ attr }) => ({
name: attr.name || 'Default name',
message: attr.message || 'Enjoy your stay!',
shadow: attr.shadow ? 'shadow' : ''
}),
html: ({ attr, data }) => `
<div title="${data.name}" class="${data.shadow}">
<h1>${data.name}</h1>
<p>Welcome ${data.name}. ${data.message}</p>
</div>
`Event listeners
Modjool is designed for simple custom elements, but sometimes it's necessary to use an event listener.
There are two main approaches to applying event listeners:
HTMLElement.oneventname = function
---
HTMLElement.addEventListener('eventname', function)
Approach 2 is often recommended, however with Modjool, approach 1 is much more suited to the task.
Approach 2 results in a new event being applied every time the body updates, therefore it's recommended
to use approach 1, which will simply replace the previous event instead of applying a duplicate event.
Internal event listeners
It's advisable to place event listeners on internal elements using the find
instance parameter, within the complete hook:
modjool.create({
tag: 'custom-element',
complete: ({ find }) => {
find`button`.onclick = event => {
console.log(event.target)
}
},
html: () => `
<button>Click me</button>
`
})
The complete hook is run after the element's body updates, meaning that the event listeners
will always be placed.
Element event listeners
To place an event listener on the whole element, using elem within the js
hook is most performant:
modjool.create({
tag: 'custom-element',
js: ({ elem }) => {
elem.onmouseover = event => {
console.log(event.target)
}
}
})