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 :-)
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 :-)
Share Improve this question asked Oct 27, 2015 at 3:54 It worked yesterday.It worked yesterday. 4,62711 gold badges50 silver badges84 bronze badges4 Answers
Reset to default 4You 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>
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/ben86foo/10/
I think the correct method for this is .blur()
So the following should suffice:
var p = document.querySelector('p');
p.addEventListener('keypress', function (e) { // you spelt addEventListener wrongly
if (e.which === 13) {
e.preventDefault();// to prevent the default enter functionality
this.blur();
}
});
You can use the onblur
or onfocusout
event:
<p onblur="myFunction()" contenteditable>
The greatest p tag of all p tags all the time
</p>
or
<p onfocusout="myFunction()" contenteditable>
The greatest p tag of all p tags all the time
</p>