Skip to content Skip to sidebar Skip to footer

Bold/unbold Selected Text Using Window.getselection()

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 wa

Solution 1:

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.

functionaddBold(){
  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-javascriptif (window.getSelection) {
    if (window.getSelection().empty) {  // Chromewindow.getSelection().empty();
    } elseif (window.getSelection().removeAllRanges) {  // Firefoxwindow.getSelection().removeAllRanges();
    }
  } elseif (document.selection) {  // IE?document.selection.empty();
  }

};
.bold-span {font-weight: bold;}
<pcontentEditable>Bold anything here and unbold it</p><buttononclick="addBold()">Bold</button>

Solution 2:

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"

Post a Comment for "Bold/unbold Selected Text Using Window.getselection()"