I have an input to which I append text (a selected emoji from Picmojs).
It's working really well but for some reason, the last edit made by my javascript code is immediately reverted when I unfocus the input.
Here's a live video example (0:10s)
I know that the popup picker from Picmojs has a built-in feature that automatically sets focus back to the element when closed, but I need to set it to another one (the input).
I managed to have it work using a timeout function for a few minutes and then I lost my fix and I'm not able to find it back.
Do you have any hints?
Here's my function:
function bind(Input,Emoji) {
var startPos = Input.selectionStart;
var endPos = Input.selectionEnd;
var length = startPos+Emoji.length
Input.value = Input.value.substring(0, startPos) +
Emoji +
Input.value.substring(endPos, Input.value.length);
Input.selectionStart = startPos + Emoji.length;
Input.selectionEnd = startPos + Emoji.length;
if (properties.hideOnEmojiSelect === false) {return}
setTimeout(() => Input.setSelectionRange(length, length), 225)
setTimeout(() => Input.focus(), 225)
}
And here's the full code:
function initialize(instance, properties, context) {
// BINDING
function bind(Input,Emoji) {
var startPos = Input.selectionStart;
var endPos = Input.selectionEnd;
var length = startPos+Emoji.length
Input.value = Input.value.substring(0, startPos) +
Emoji +
Input.value.substring(endPos, Input.value.length);
Input.selectionStart = startPos + Emoji.length;
Input.selectionEnd = startPos + Emoji.length;
if (properties.hideOnEmojiSelect === false) {return}
setTimeout(() => Input.setSelectionRange(length, length), 225)
setTimeout(() => Input.focus(), 225)
}
window.addEventListener('load', (event) => {
//DEFINE TRIGGER BUTTON + INPUT
var Button = document.getElementById(properties.button_id);
var Reference = document.getElementById(attach_to);
var Input = ""
if (properties.input) {Input = document.getElementById(properties.input_id);}
// Create the picker
const picker = createPopup({
hideOnClickOutside: properties.hideOnClickOutside,
hideOnEmojiSelect: properties.hideOnEmojiSelect,
hideOnEscape: properties.hideOnEscape,
showCloseButton: properties.showCloseButton
}, {
// The element that triggers the popup
triggerElement: Button,
// The element to position the picker relative to - often this is also the trigger element,
referenceElement: Reference,
});
//
// EVENTS
//
// Event : Select
picker.addEventListener('emoji:select', event => {
if (properties.input) {setTimeout(() => bind(Input,event.emoji), 225)}
instance.publishState("selected", event.emoji);
instance.triggerEvent("selected");
});
// Event : Opened
picker.addEventListener('picker:open', event => {
instance.triggerEvent("opened");
});
// Event : Closed
picker.addEventListener('picker:close', event => {
instance.triggerEvent("closed");
});
// Event : Click
Button.addEventListener('click', event => {
if (properties.disabled === false) {picker.toggle();}
});
});
}