Define cursor on element

I am trying to explain my problem.

I have a <div contenteditable="true" id="my_editeur> where I defined the keyword" event ", which allows me to add" p "when the user presses" enter ".

It works well, but I would like to define a cursor on this new "p-element", because currently my cursor remains on the first "p" element.

I tried using the jquery focus function, but it seems that we cannot use this function for the 'p elements.

Do you know how I can do this to solve my problem?

Many thanks for your help.

My code is:

 $('#my_editeur').keypress(function(e){ if(e.keyCode == 13) { e.preventDefault(); $(this).append('<p ><br /></p>'); } }); 
+4
source share
4 answers

Not sure if this will work, but have you tried adding tabindex="0" to <p> ? This meant that he could focus in most browsers.

+1
source

When creating a paragraph, enable non-breaking space.

 var newP = $("<p>&#160;</p>").get(0); 

For Firefox browsers and standards,

 var rng = document.createRange(); rng.selectNodeContents( newP ); var sel = document.defaultView.getSelection(); sel.removeAllRanges(); sel.addRange(rng); 

For IE,

 var rng = document.body.createTextRange(); rng.moveToElementText( newP ); rng.select(); 
+1
source

Correct me if I am mistaken, but you want the text to be entered into the <p> element, as if it were <input> or <textarea> ? If so, here is the hack I put together. This is obviously not entirely, just a proof of concept.

 <!doctype html> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready( function(){ $('#textbox').click( function(){ $(this).css('border','1px solid #f00'); $('#mytext').focus(); } ); $('#mytext').keypress( function(event){ if(event.keyCode==13){ $('#textbox').append('<br>'); } else{ $('#textbox').append(String.fromCharCode(event.which)); } } ); } ); </script> <style type="text/css"> #mytext{ position: fixed; top: -100px; left: 0; } </style> </head> <body> <input type="text" id="mytext" tabindex="0"> <div id="textbox"><span>hello</span></div> </body> </html> 

You can click on the <div> that says hello and type more text into it.

0
source

Can't you set the selection to DOMRange inside the new <p>? I suppose doing window.getSelection () to retrieve the current DOMRange and change its startContainer, endContainer, startOffset, endOffset.

0
source

Source: https://habr.com/ru/post/1303557/


All Articles