Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus out an editable p tag with pure javascript

I have following html

<p contenteditable>The greatest p tag of all p tags all the time</p>

and this js

var p = document.querySelector('p');

p.addEventListner('keypress', function (e) {
    if (e.which === 13) {
        //this.focusout() ??;
    }
});

DEMO

But this thing doesn't work. How do i focusout the p tag with enter hit. No jquery Please. Thanks :-)

like image 471
It worked yesterday. Avatar asked Nov 27 '25 15:11

It worked yesterday.


2 Answers

You misspelled Listener so the keypress wasn't being caught. You'll also want to prevent keypress like this

var p = document.querySelector('p');
p.addEventListener('keypress', function (e) {
    if (e.which === 13) {
        this.blur();
        e.preventDefault();
    }
});
<p contenteditable>The greatest p tag of all p tags all the time</p>
like image 154
SuperPrograman Avatar answered Nov 30 '25 05:11

SuperPrograman


Try using event.preventDefault() , creating input element having width , height set to 0px , opacity set to 0 . If event.keyCode equals 13 , call .focus() on input with opacity 0

var p = document.querySelector('p');

p.onkeypress = function(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    document.getElementById("focus").focus();
  }
};
#focus {
  width: 0;
  height: 0;
  opacity: 0;
}
<p contentEditable>The greatest p tag of all p tags all the time</p>
<input id="focus" />

jsfiddle https://jsfiddle.net/ben86foo/10/

like image 38
guest271314 Avatar answered Nov 30 '25 05:11

guest271314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!