Skip to content

Instantly share code, notes, and snippets.

@doiftrue
Created January 14, 2024 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doiftrue/c1beb1d4c4385602a0f08edd559606de to your computer and use it in GitHub Desktop.
Save doiftrue/c1beb1d4c4385602a0f08edd559606de to your computer and use it in GitHub Desktop.
[wpkama embed] https://wp-kama.com/2310 Tab Symbol (\t) in Textarea When Pressing TAB Key
/**
* \t (tab ⇆ tabulation) symbol in textarea when pressing tab on the keyboard.
*
* Adds initial indentation for selected text when pressing the `Tab` key.
* Or removes the initial indentation (4 spaces or TAB) when pressing `Shift + Tab`.
*
* @Author Kama (wp-kama.ru)
* @version 4.3
*/
document.addEventListener( 'keydown', function( event ){
if( 'TEXTAREA' !== event.target.tagName ){
return
}
// not tab
if( event.code !== 'Tab' ){
return
}
event.preventDefault()
// Opera, FireFox, Chrome
let textarea = event.target
let selStart = textarea.selectionStart
let selEnd = textarea.selectionEnd
let before = textarea.value.substring( 0, selStart )
let slection = textarea.value.substring( selStart, selEnd )
let after = textarea.value.substr( selEnd )
let slection_new = ''
// remove TAB indent
if( event.shiftKey ){
// fix selection
let selectBefore = before.substr( before.lastIndexOf( '\n' ) + 1 )
let isfix = /^\s/.test( selectBefore )
if( isfix ){
let fixed_selStart = selStart - selectBefore.length
before = textarea.value.substring( 0, fixed_selStart )
slection = textarea.value.substring( fixed_selStart, selEnd )
}
let once = false
slection_new = slection.replace( /^(\t|[ ]{2,4})/gm, ( mm )=>{
if( isfix && ! once ){
once = true // do it once - for first line only
selStart -= mm.length
}
selEnd -= mm.length
return ''
})
}
// add TAB indent
else {
selStart++
// has selection
if( slection.trim() ){
slection_new = slection.replace( /^/gm, ()=>{
selEnd++
return '\t'
})
}
else {
slection_new = '\t'
selEnd++
}
}
textarea.value = before + slection_new + after
// cursor
textarea.setSelectionRange( selStart, selEnd )
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment