Skip to content

Instantly share code, notes, and snippets.

@daverogers
Created November 5, 2024 10:11
Show Gist options
  • Save daverogers/a02eef6660f46b388a979b68ec416ae2 to your computer and use it in GitHub Desktop.
Save daverogers/a02eef6660f46b388a979b68ec416ae2 to your computer and use it in GitHub Desktop.
Wrap Highlighted Input Text With Quotes
<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