How to implement Drag in Svelte?
In this article, we learn how to implement Drag in Svelte. Before starting, you need to create a project in Svelte using the npx
command.
npx degit sveltejs/template Drag
You need to install npx
if you haven't. Drag
is the name of our Project.
npx degit sveltejs/template Drag
yarn install
Default yarn dev
will run on 8080
port. We need to change it to 5000
. We can handle the port from package.json
and modify the script tag.
{
..
..
..
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public --no-clear -p 5000"
},
..
..
..
}
Run yarn dev
and the application points to 5000 port.
Create a new component, Drag.svelte
under the src
folder. And add the following content
<script>
export let left = 20
export let top = 20
let dragging ;
function start() {
dragging = true
}
function stop() {
dragging = false
}
function moveComponent( event ) {
if ( dragging ) {
left = left + event.movementX;
top = top + event.movementY;
}
}
</script>
<svelte:window on:mouseup="{stop}" on:mousemove="{moveComponent}"></svelte:window>
<div style="margin-left: {left}px; margin-top: {top}px;" on:mousedown="{start}" class="drag">
<h1 style="margin: 20 20 20 20; margin-left: 20px; margin-right: 20px; user-select: none">
Drag Component
</h1>
</div>
<style>
.drag {
position: absolute;
border: 2px black solid;
cursor: move;
}
</style>
Open the App.svelte
and replace the content with the following:
<script>
import Drag from "./Drag.svelte";
</script>
<main>
<Drag />
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
And thats all for now.
Please subscribe to follow more articles.