Clear Text Selection with JavaScript

Clear Text Selection with JavaScript

if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}

Credit to Mr. Y.

Clear text selection in shiny

We can implement an onclick event for the reset button calling removeAllRanges(). Please check the following:

library(shiny)

text1 <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce nec quam ut tortor interdum pulvinar id vitae magna. Curabitur commodo consequat arcu et lacinia. Proin at diam vitae lectus dignissim auctor nec dictum lectus. Fusce venenatis eros congue velit feugiat, ac aliquam ipsum gravida. Cras bibendum malesuada est in tempus. Suspendisse tincidunt, nisi non finibus consequat, ex nisl condimentum orci, et dignissim neque est vitae nulla."
text2 <- "Aliquam ut purus neque. Maecenas justo orci, semper eget purus eu, aliquet molestie mi. Duis convallis ut erat at faucibus. Quisque malesuada ante elementum, tempor felis et, faucibus orci. Praesent iaculis nisi lorem, non faucibus neque suscipit eu. Ut porttitor risus eu convallis tristique. Integer ac mauris a ex maximus consequat eget non felis. Pellentesque quis sem aliquet, feugiat ligula vel, convallis sapien. Ut suscipit nulla leo"
highlight <- '
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection) {
text = document.selection.createRange().text;
}
return text;
}

document.onmouseup = document.onkeyup = document.onselectionchange = function() {
var selection = getSelectionText();
Shiny.setInputValue("mydata", selection);
};
'
ui <- bootstrapPage(
tags$script(HTML(highlight)),
fluidRow(
column(4,
tags$h1("Text to code"),
tags$h2("From table"),
tableOutput("table"),
tags$h2("From raw text"),
verbatimTextOutput("text"),
actionButton("vClear", "Clear Selection", onclick = 'const reset = function(){Shiny.setInputValue("mydata", ""); window.getSelection()?.removeAllRanges();}; reset();')
),
column(4,
tags$h1("Coding options"),
actionButton("code1", "Assign selected text to Code1"),
tags$h1("Code1 output"),
verbatimTextOutput("selected_text")
)
)
)

server <- function(input, output, session) {
coded_text <- reactiveVal()

observeEvent(input$code1, {
coded_text(c(coded_text(), input$mydata))
})

observeEvent(input$vClear, {
coded_text(NULL)
})

output$table <- renderTable({
data.frame(paragraph = 1:2, text = c(text1, text2))
})

output$text <- renderText(paste(text1, text2))

output$selected_text <- renderPrint({
coded_text()
}) # |> bindEvent(input$code1)
}

shinyApp(ui = ui, server = server)

result

PS: in shiny you should try to avoid global variables and use reactiveVal or reactiveValues instead.

How to remove text selection from selected text which is coming by default on page load?

You should clear text selection once you display your control; you can do this by calling this function (should be fully cross-browser):

function clearSelection() {
if (window.getSelection) window.getSelection().removeAllRanges();
else if (document.selection) document.selection.empty();
}

Is there a function to deselect all text using JavaScript?

Try this:

function clearSelection()
{
if (window.getSelection) {window.getSelection().removeAllRanges();}
else if (document.selection) {document.selection.empty();}
}

This will clear a selection in regular HTML content in any major browser. It won't clear a selection in a text input or <textarea> in Firefox.

How to clear text selection in Mobile Safari with JavaScript?

This has been a known bug in Mobile Safari since 2010! http://www.openradar.me/8707236

The year is now 2018 and this is still a bug. (iOS 10.2.2)

In areas where it was not needed, removing event.preventDefault() helped.

Can't clear text selection from textarea

Hacky solution

I still don't fully understand why this is happening, but found a workaround solution for now:

In the textarea's onBlur callback, simply use the following code:

if (textArea2Ref.current) {
// if there's a range selection
if (textArea2Ref.current.selectionStart !== textArea2Ref.current.selectionEnd) {
// reset the range
textArea2Ref.current.selectionStart = textArea2Ref.current.selectionEnd;

// blur the textarea again, because setting the selection focuses it?
textArea2Ref.current.blur();
}
}

Remove the format of selected text only

Just get the text selection, and keep track of what style was applied previously (bold/italic). If the style has already been applied, remove the style only from the selected text.

document.getElementById('bold').addEventListener('click', () => edit('STRONG'));
document.getElementById('italic').addEventListener('click', () => edit('EM'));

// Variables to track what style has been applied
let textBold = false;
let textItalic = false;

function edit(format) {
// Getting selected text
let selectedText = getSelection();

// Create new element
let el = document.createElement('span');

// Applying style depending on the format
if (format === 'STRONG') {
// Assignation to retain previous style
el.style.fontStyle = (textItalic? 'italic' : 'normal');
if (textBold === false) {
el.style.fontWeight = 'bold';
textBold = true;
} else {
el.style.fontWeight = 'normal';
textBold = false;
}
}

else if (format === 'EM') {
// Assignation to retain previous style
el.style.fontWeight = (textBold ? 'bold' : 'normal');
if (textItalic === false) {
el.style.fontStyle = 'italic';
textItalic = true;
} else {
el.style.fontStyle = 'normal';
textItalic = false;
}
}

el.innerHTML = selectedText.toString();
let range = selectedText.getRangeAt(0);
range.deleteContents();
range.insertNode(el);

}
<button id="bold">B</button>
<button id="italic">I</button>
<div contentEditable="true">Lorem</div>

How do I remove selected text from an input control?

Depending on browser compatibility (ie9+ and others) you could use selectionEnd, selectionStart:

$("#btnRemove").click(function () {
var ele = document.getElementById('txtbox');
var text = ele.value;

text = text.slice(0, ele.selectionStart) + text.slice(ele.selectionEnd);
ele.value = text;
});

Working Fiddle in Chrome



Related Topics



Leave a reply



Submit