Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a <div> contentEditable on doubleclick using Svelte?

I'm brand new to Svelte (3.0+)...and for my latest project, I'd like to emulate the functionality of many "todo" lists that allow you to edit todo items previously submitted by double-clicking on them (Here's an example of the functionality I'm looking for).

I imagine, the first step is figuring out how to make a div contentEditable with Svelte with the on:dblclick event handler. I'm having trouble figuring out the syntax for this task (though I can do it with vanilla javascript).

Here's the Svelte code I have so far: ( Here it is on CodeSandBox.io - see page: CEDiv.svelte)

<script>
function edit(event) {
    //update db functionality goes here
    //alert("you've 'submitted' your edit")
}

function handleDblClick() {
    //I need help HERE...and probably on the div on:dblclick down below....
}
function handleKeydown() {
    key = event.key;
    keyCode = event.keyCode;
    //submit the div's content to the edit function if enter or tab is pressed.
    keyCode == 13 || keyCode == 9 ? edit(event) : null;
}
</script>
<style>
div.read-mode {
    padding:10px;
    border:1px solid green;
    height:30px;
    line-height:30px;
    width:500px;
    margin:0 auto;
}
div.edit-mode {
    padding:10px;
    background: lightgreen;
    border:3px solid green;
    height:26px;
    line-height:26px;
    width:496px;
    margin:0 auto;
}
</style>
<div on:dblclick={handleDblClick} class="read-mode" on:keydown={handleKeydown} contentEditable="false">
    I want this Div to be editable one double click.
</div>

Thanks in advance for your help!

like image 232
Doomd Avatar asked Mar 02 '23 23:03

Doomd


1 Answers

Add a boolean variable

let editable = false;

which will be changed inside your handler

function handleDblClick(event) {
  editable = true; // or use  editable=!editable  to toggle
}

bind your editable variable inside the attribute,
and take a look how to dynamically toggle the class "edit-mode" using a ternary operator

<div 
  on:dblclick={handleDblClick} 
  class={editable ? 'edit-mode': 'read-mode'} 
  on:keydown={handleKeydown}
  contenteditable={editable}>
    I want this Div to be editable on double click.
</div>

Here's a CodeSandbox fork

like image 88
Roko C. Buljan Avatar answered Mar 05 '23 16:03

Roko C. Buljan