7 DOM Interactions

 

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 tick function 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 dialog element
  • 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 then modify the properties of these DOM elements and call methods on them.

This chapter presents several such scenarios.

7.1  Inserting HTML

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.

7.2  Actions

 
 
 

7.2  tick function

 
 

7.3  Implementing a dialog component

 
 
 

7.4  Drag and drop

 
 
 

7.5  Building the Travel Packing app

 
 
 

7.6  Summary

 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest