I've created a function that allows a user to align highlighted/selected text right/left/center, but it doesn't seem to be working.
function doCenter() {
{
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.textAlign = "center";
span.appendChild(selectedText);
selection.insertNode(span);
}
}
I've tried this with a separate function that does the same thing, except it highlights the words instead of aligning them, and it works:
function highlighter() {
{
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selectedText);
selection.insertNode(span);
}
}
Can anyone tell me what's wrong with the first code?
span is an inline element whereas only block elements may have their child content aligned. Either use div or p instead of a span, or set
span.style.display = 'block';
Related
I'm trying to make a simple text editor so users can be able to bold/unbold selected text. I want to use Window.getSelection() not Document.execCommand(). It does exactly what I want but when you bold any text, you can't unbold it. I want it in a way that I can bold and unbold any selected text. I tried several things but no success.
function addBold(){
const selection = window.getSelection().getRangeAt(0);
const selectedText = selection.extractContents();
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selectedText);
selection.insertNode(span);
};
.bold-span {font-weight: bold;}
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>
This is close to what you want but groups words together so an unselect will remove from whole word. I have not been able to complete this as I have to go, but should be a good starting point.
function addBold(){
const selection = window.getSelection().getRangeAt(0);
let selectedParent = selection.commonAncestorContainer.parentElement;
//console.log(parent.classList.contains("bold-span"))
//console.log(parent)
let mainParent = selectedParent;
if(selectedParent.classList.contains("bold-span"))
{
var text = document.createTextNode(selectedParent.textContent);
mainParent = selectedParent.parentElement;
mainParent.insertBefore(text, selectedParent);
mainParent.removeChild(selectedParent);
mainParent.normalize();
}
else
{
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selection.extractContents());
//selection.surroundContents(span);
selection.insertNode(span);
mainParent.normalize();
}
//selection is set to body after clicking button for some reason
//https://stackoverflow.com/questions/3169786/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();
}
};
.bold-span {font-weight: bold;}
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>
var span = '';
jQuery(function($) {
$('.embolden').click(function(){
var highlight = window.getSelection();
if(highlight != ""){
span = '<span class="bold">' + highlight + '</span>';
}else{
highlight = span;
span = $('span.bold').html();
}
var text = $('.textEditor').html();
$('.textEditor').html(text.replace(highlight, span));
});
});
You could define a function like this where the name of your class is "embolden"
I want to build a unique, simple text editor. With this JS code I can get the selected text from the textarea, but how may I give styling to it (font-weight, font-style etc.) with buttons (Bold, Italic)?
var selectedText = '';
function getText(e) {
selectedText = (document.all) ? document.selection.createRange().text : document.getSelection();
alert(selectedText);
}
document.onmouseup = getText;
if (!document.all) document.captureEvents(Event.MOUSEUP);
I experimented with adding the following code into the getText function. It works at some point, the selected text is wrapped into a span, the span gets the .new-span, bold-style and italic-style classes (btn onclick), but still the styling does not apply to the selected text in the textarea, the change is not visible.
var selectedText = '';
function getText(e) {
selectedText = (document.all) ? document.selection.createRange().text : document.getSelection();
var newSpan = document.createElement("span");
newSpan.classList.add("new-span");
newSpan.innerText += selectedText;
console.log(newSpan);
artParag.appendChild(newSpan);
var boldStyleBtn = document.querySelector(".bold-style-btn");
var italicStyleBtn = document.querySelector(".italic-style-btn");
boldStyleBtn.addEventListener("click", function boldStyle() {
newSpan.classList.toggle("bold-style");
alert(selectedText);
});
italicStyleBtn.addEventListener("click", function italicStyle() {
newSpan.classList.toggle("italic-style");
alert(selectedText);
});
}
document.onmouseup = getText;
if (!document.all) document.captureEvents(Event.MOUSEUP);
(the CSS):
.bold-style {
font-weight: 700;
}
.italic-style {
font-style: italic;
}
Is this a good direction? Thank you in advance for your help.
In my application (a basic WYSIWYG text editor) I have a bold button which works, but I need to be able to de-bold text also.
Does anyone have an idea on how to do this?
My code
function bolden ()
{
var range = window.getSelection().getRangeAt(0);
var newNode = document.createElement("b");
range.surroundContents(newNode);
}
function unbolden ()
{
var range = window.getSelection().getRangeAt(0);
$(range).contents().unwrap()
}
Try
function unbolden() {
var range = window.getSelection().getRangeAt(0);
var node = $(range.commonAncestorContainer)
if (node.parent().is('b')) {
node.unwrap();
}
}
Note: If the selected range is under a b element then then entire contents of the element will be unwrapped not just the selected text
I'm trying to create a fairly simple text editor (bold, italic, indent) and need to be able to toggle the class associated with the button on click. I have this code:
var selected = function ()
{
var text = '';
if (window.getSelection) {
text = window.getSelection();
}
return text;
}
$('textarea').select(function(eventObject)
{
console.log(selected().toString());
var selectedtext = selected().toString();
$('#bold-button').click(function () {
$(selectedtext).addClass('bold-text');
});
});
And I can get the selected text to print, but can't get the class added. I've seen other solutions that add the class on click to the entire textarea, but I dont need that. Any help?
You could use surroundContents() like below. Before demo here http://jsfiddle.net/jwRG8/3/
function surroundSelection() {
var span = document.createElement("span");
span.style.fontWeight = "bold";
span.style.color = "green";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
But this is not supported less than IE9. And I worked on text selections before and I found them in consistent. Tim Down is very much experienced on selections and most of the answers in SO related to Selections are given my him. He has written a plugin called rangy. You mat try it at https://code.google.com/p/rangy/
Because you are selecting text directly, there is no element to add the class on. textNodes cannot have classes. Instead, try wrapping the text in an element:
$('textarea').select(function(eventObject) {
console.log(selected().toString());
var selectedtext = selected().toString();
$(selectedtext).wrap('<span />').parent().addClass('bold-text');
})
Or you could just wrap it in a b tag, without the class:
$(selectedtext).wrap('<b/>');
By using following code I am getting the selected text's startindex and the selected text itself. I am storing them in a local database. I am changing the selected text background color to yellow.
var mainDiv = document.getElementsByTagName("body")[0];
var sel = getSelectionCharOffsetsWithin(mainDiv);
var selectedText = window.getSelection();
location.href = selectedText + '*' + sel.start; // this is to call iOS function.
var range = window.getSelection().getRangeAt(0);
var span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.setAttribute("id", sel.start);
range.surroundContents(span);
Now, I am doing something else, and again I come back to same page. Here now I want to show previously selected text as highlighted.
Use Rangy , nothing beats it , does exactly what your trying
Rangy
Have a look at this demo