Reading Selected Text in Svelte

- 2 minutes read

Svelte lets us conveniently read text selected by users.

We can also update a variable each time the selection changes.

Here’s an example, where selection stores the current text selection:

<script>
    import { onMount } from 'svelte';

    let selection = ``;

    onMount(() => {
        // Once the component is mounted, we can access the document:
        document.addEventListener(`selectionchange`, () => {
            selection = document.getSelection();
        });
    });
</script>

<p>This is an example sentence.</p>

<p>Selected text: "{selection}"</p>

The selection variable will be automatically updated with the most recent text selection each time the user changes their selection.

Link to this section Conclusion

There’s several ways of doing this, but many of the solutions I’ve seen online are outdated. And I couldn’t find any examples specifically for Svelte.

Anyway, I hope you find this snippet useful for working with text selections in your Svelte app!