Click here to Skip to main content
15,898,036 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have been trying to build a web-based text editor. And as part of the process, I am trying to dynamically create and modify elements based and keystroke events for font editing. In this particular jsfiddle example I'm trying to create a strong element upon hitting CRTL+b and setting the focus/caret inside the strong element so that subsequent text entered will be part of the bold element and hence will have bold text. But my code is just creating a strong element but not transferring the focus hence no text is getting bolder.

What I have tried:

In the below code I'm creating event listener to capture keystroke events

p=document.getElementsByTagName("p")[0];

//console.log(p)

// adding eventlistener for keydown
p.addEventListener("keydown",listener);

// eventlistenerr callback function
function listener(){
  e=window.event;
  if(e.ctrlKey && e.keyCode==66)
    {
      console.log("CTRL+B");

      // creating bold element
      belm=document.createElement("strong");
      belm.setAttribute("contenteditable","true")
      p.appendChild(belm);

      //bug below
      // setting focus inside bold element
      setfocus(belm,0);
      e.preventDefault();
    }
}


Here is the function for setting the focus.

function setfocus(context, position){
    var range = document.createRange();
    position =position || 0;
    var sel = window.getSelection();
    range.setStart(context, position);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    context.focus();
}


However, I have not doubt that the function which sets focus is faulty, because in the fiddle if you observe, I have created a separate setup just to test this out. Click on the button "Click Here" and the focus dynamically shifts to paragraph element without any hassle. I am unable to figure out what is going wrong. Please Help!

Click here for live example.
Posted
Updated 6-Nov-17 15:12pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900