chapter seven
This chapter covers:
- Inserting HTML from string variables
- Avoiding cross-site scripting attacks from untrusted HTML
- Using “actions” to run code when an element is added to the DOM
- Using the
tickfunction to modify the DOM after Svelte updates
- Implementing a dialog component
- Implementing drag and drop
Sometimes Svelte applications need to tap into DOM functionality that is not directly supported by Svelte. Examples include
- Moving focus to an input where the user is expected to enter data
- Setting the cursor position and selected text inside an
input
- Calling methods on a
dialogelement
- Allowing users to drag particular elements onto others
All of these require going beyond simply writing the HTML to be rendered inside a Svelte component definition. Svelte supports this by providing access to the DOM elements it creates. Component code can modify the properties of these DOM elements and call methods on them.
This chapter presents several such scenarios.
Typically Svelte components render HTML by directly specifying HTML elements in .svelte files. However, sometimes it is convenient to obtain the HTML as a string from a source outside the component definition. Let’s explore a scenario where this is useful.