How to simulate keypress inside of a contenteditable div Programatically?
I want to remove characters programatically with a jQuery script without any human typing.
I would like to delete some characters from the end of the span tag with simulating a Backspace keypress inside of the contenteditable div.
<div class="editor" contenteditable="true">
<span>This is a span!!</span>
</div>
So the result would be something like this:
This is a span
I wouldn't like to rewrite the text. I need to simulate backspace keypress. Tested with this code, but nothing happened.
$(document).ready(function(){ // after the website loaded
// I want to trigger a keypress (backspace key)
// inside of the contenteditable div Programatically
$('.editor').trigger(jQuery.Event('keypress', { keycode: 8 }));
});
Can you help me?
I used some part of code that was mentioned in the comments: SO answer - Yuri
Here is the part that triggers the keydown event
$(document).ready(function(){ // after the website loaded
// I want to trigger a keypress (backspace key)
// inside of the contenteditable div Programatically
var e = jQuery.Event("keydown");
e.which = 8; // backspace key
$(".editor").trigger(e);
});
After that, I created a handler to .editor element
$(".editor").keydown(function(e) {
if (e.originalEvent === undefined) {
console.log('triggered programmatically');
} else {
console.log('triggered by the user');
}
console.log("Key pressed:" + e.which);
if(e.which == 8) {
// do your stuff
}
});
I also, put a validator to check if the event was trigged by user or programmatically.
Related
In my custom-editor wrapping up the code in <pre> tags works fine. I would like to visually organize the pasted code for better readability. For that I need blank lines in between chunks of code. But instead of a empty line, when I press Enter, the whole code block breaks into two, with new one wrapped in its own pre-tag. The code below is supposed to be in a single-block with an empty line between example_function and another_example_function()
FYI, the contenteditable class is set to have style="display:inline-block" to prevent div.wrapper on every line. Possibly relevant CSS info - pre { white-space: pre-wrap;}. I am on chrome 83.xx. Let me know if you need any more info. Below is what I tried and failed:
//there could be several code-blocks so running a loop to get all
let preTags = document.querySelector('.custom_editor').querySelectorAll('pre')
if (preTags) {
preTags.forEach(function(item) { // attaching an event-listener to each code block
item.addEventListener('click', function(e) {
if (e.keyCode === 13) { //on enter just need a empty new line
document.execCommand('insertHTML', false, '<br>');
return false;
}
})
}
}
HTML
<div class="content" style="display:inline-block;" contenteditable="true"></div>
The nested pretags eg. contenteditable>pre do not seem like an ideal setup for events like 'keypress', 'keydown' and 'keyup' as they did respond to these events in my case. The 'click' event within pretags worked but did not process the if (e.key === 'Enter') check, so I did not follow that route.
Instead of listening to events for each pretag, I attached a listener to the container only and all of sudden my custom setting for enter-event was working inside and outside all pretags within container. Eventually I can get the empty lines within my pretags on pressing the Enter key.
document.querySelector('.custom_editor').addEventListener('keypress', someFunc)
function someFunc(e){
if (e.key === 'Enter') {
document.execCommand('insertHTML', false, "<br>");
e.preventDefault()
}
}
I have below codes to delete input text.
$(document).on('click', "button[id='del_btn']", function(event) {
$("input[id='lvl4_text1']").select()
$("input[id='lvl4_text1']").focus()
//trigger backspace keycode 8, keydown and keyup envent to input
var e = $.Event('keydown', {
keyCode: 8,
which: 8
})
$("input[id='lvl4_text1']").trigger(e)
e = $.Event('keyup', {
keyCode: 8,
which: 8
})
$("input[id='lvl4_text1']").trigger(e)
});
//I can see keyup and keydown event was triggered successfully.
$(document).on('keyup', "input[id='lvl4_text1']", function(event) {
console.log("level 4 text keyup" + event.which)
});
$(document).on('keydown', "input[id='lvl4_text1']", function(event) {
console.log("level 4 text down" + event.which)
});
it is quite straightforward and simple, but the text in input was not deleted.
I am using chrome55 and jquery1.8.
I do not want a workaround to delete input text, just would like to know why backspace keyboard evnet was triggerd already, but input text was not deleted.
and I tried trigger delete key(keycode 46) event also, nothing changed as same. I also trigger 'a'(keycode 65) to input, but input text can not be replaced.
I am newbie to js/jquery, can any one help?
I recommend splitting the input into an array, removing the last part of the array
myarray.pop()
Then joining it back into a regular sentence, to then focus on the input.
Also, .trigger() triggers it for jQuery, but does not create the actual event as though the delete button is being pressed on your keyboard.
I'm trying to trigger a paste event in a textarea with jQuery, but this subject is quite new to me.
I've seen how one can manually trigger a keydown event simulating pressing a specific key like this:
var e = $.Event("keydown")
e.which = 50
$('#textarea1').trigger(e)
But how can I manually trigger a paste event with a provided string of text that effectively simulates a Ctrl+V or right-click > paste of a string like "Foobar"?
I have tried to simply set the value of textarea but this does not trigger a paste event.
EDIT:
I have also tried this (to simulate Ctrl+V) but no luck (ref):
e = $.Event("keydown");
e.which = 86; // 'V' key
e.ctrlKey = true;
$("input").trigger(e);
I realise this is an old question, but you were on the right track.
To manually trigger a Paste event using jQuery, you need to use the paste event type, e.g.:
const e = $.Event('paste');
$('#textarea').val('some text').trigger(e);
or:
$('#textarea').val('some text').trigger('paste');
Here is a solution you can try:
$('body').on('paste',function(e) {
e.preventDefault();
var text = (e.originalEvent || e).clipboardData.getData('text/plain');
alert(text);
});
I am using a site that has a search box and I would like it so when you press the space bar but don't have the search text box selected, the search text box gets focus and has it's text cleared. I have it about done, but the check to see if the search box has focus isn't functioning properly. Any suggestions on my code? As is, if you press the space bar, it clears the search box, even if you're typing in the search box.
document.addEventListener('keydown', function (event) {
if (event.keyCode == 32) {
if ($('#searchTextBox').not(':focus')) {
$("#searchTextBox").focus().select();
}
}
});
While you delegate a keydown event on the document, you can also check if the source/target is the textbox itself by using event.target. If the event comes from the text field, just ignore it.
$(document).on('keydown', function (event) {
if (event.which == 32 && event.target.id != 'searchTextBox')
$("#searchTextBox").focus().select();
});
Working example : https://jsfiddle.net/DinoMyte/mdu5fxkq/3/
Maybe this will work
$(document).ready(function(){
$(document).on('keydown',function(event){
if(event.keyCode==32){
if(!$('#search').is(':focus')) {
$('#search').focus().select();
}
}
});
});
Grettings!
Even Simpler
Check for the keyCode as 32 is for spacebar and you can use any other by using its code
$(document).on('keydown', function (event) {
if (event.keyCode== 32) {
$("#searchTextBox").focus().select();
}
});
How can I mimic pressing the enter button from within a <input>, using jQuery?
In other words, when a <input> (type text) is in focus and you press enter, a certain event is triggered. How can I trigger that event with jQuery?
There is no form being submitted, so .submit() won't work
EDIT
Okay, please listen carefully, because my question is being misinterpreted. I do NOT want to trigger events WHEN the enter button is pressed in textbox. I want to simulate the enter button being pressed inside the textbox, and trigger this from jQuery, from $(document).ready. So no method involving on.('keypress')... or stuff like that is what I'm looking for.
Use keypress then check the keycode
Try this
$('input').on('keypress', function(e) {
var code = e.keyCode || e.which;
if(code==13){
// Enter pressed... do anything here...
}
});
OR
e = jQuery.Event("keypress")
e.which = 13 //choose the one you want
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
DEMO
Try this:
$('input').trigger(
jQuery.Event('keydown', { which: 13 })
);
try using .trigger() .Docs are here
Instead of using {which:13} try using {keyCode:13}.
$('input').trigger(jQuery.Event('keydown', {keyCode:13}));