Created
November 5, 2024 10:11
-
-
Save daverogers/a02eef6660f46b388a979b68ec416ae2 to your computer and use it in GitHub Desktop.
Wrap Highlighted Input Text With Quotes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
// i always wanted a way to mimic IDEs in web forms, where i can wrap highlighted text with quotes | |
// or any other characters you'd typically want to wrap (parens, backticks, curly brackets, etc) | |
// this can be easily adjusted to accomodate any/all characters you want to wrap with | |
// (i just happened to be implementing this in a Vue project, but you can use it in vanilla js) | |
const keydown = (event) => { | |
const input = event.target; | |
const selectionStart = input.selectionStart; | |
const selectionEnd = input.selectionEnd; | |
const selectedText = input.value.substring(selectionStart, selectionEnd); | |
if (selectedText && event.key === '"') { | |
event.preventDefault() | |
input.value = input.value.slice(0, selectionStart) + `"${selectedText}"` + input.value.slice(selectionEnd); | |
input.setSelectionRange(selectionStart + 1, selectionEnd + 1); | |
} | |
} | |
</script> | |
<template> | |
<input placeholder="Search" @keydown="keydown" /> | |
</template> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment