Inserting Text At Cursor Location With Quill.js - javascript

I am trying to add a custom piece of functionality ("module") to quill.js and cannot seem to do it. Here is what I need:
If want to add a button that inserts a template replacement variable... say
something like {{company}} at the location of the cursor in the
editor, is that currently possible with the API - I thought I could do
it using insertText but I cant seem to get it to work.
Thanks

What I ended up doing in a very similar setup:
let mergeFieldText = '{{company}}';
var selection = this._quill.getSelection(true);
this._quill.insertText(selection.index, mergeFieldText);

You should be able to do this with insertText but you might need to use getSelection to get the cursor location. The object returned by getSelection will have an index and length key. Adding the button and necessary click handler will be up to the implementor. Note focus should be returned back to the editor before calling getSelection with focus or simply passing true to getSelection.

This code snippet is to add symbol at cursor position with a custom button with Quill.js.
First declare quill variable:
var quill = new Quill('.editor', {
theme: 'snow'
});
With button click event, add symbol at caret position.
$('.symbols').click(function(){
quill.focus();
var symbol = $(this).html();
var caretPosition = quill.getSelection(true);
quill.insertText(caretPosition, symbol);
});

For any of you still having problems with this, know that if you have a bootstrap modal showing when trying to focus on the Quill to be able to use method getSelection(), you first need to close the modal before forcing focus on the quill instance.

Related

Handlebars form template, input loses focus when updates using keyup

How would you go about updating a form template (handlebars) each time the data updates and keep the input element focused? In my code sample you will find a form field to which is attached a keyup event listener that updates the data.
But on each update I am re-rendering the form which causes the input to lose focus.
JavaScript
import "./styles.css";
import $ from "jquery";
import Handlebars from 'handlebars';
const updateHtml = data => {
const app = $('#app');
const html = template(data);
app.html(html);
}
const app = $('#app');
const data = {
foo: 'default value',
}
const template = Handlebars.compile(`<form><input type="text" id="foo" value="{{foo}}"></form>`);
updateHtml(data);
app.on('change keyup', function(e){
const val = $(e.target).val();
data.foo = val;
updateHtml(data);
});
I have created a codesandbox for you to test https://codesandbox.io/s/magical-leftpad-ry2lx?file=/src/index.js
Try typing in the input and you will find it loses focus after a keyup. So, how to solve this problem so that I can write in the input and the data object updates itself according to the inbox?
Update
I would like to provide more context on the actual application I am developing. I cam creating a complex form that includes, checkboxes, radio buttons, repeater fields which changes inputs depending on another input (conditional fields).
I do not want to update dom elements (adding/inserting/removing) by event listeners. Dom should update when data updates. That is why I am using handlebars templating system.
I am not sure that this is the best implementation for what you want to achieve. As the complexities of the form have been left out of the example, it is difficult to properly assess this solution and to propose an alternative.
The problem with this implementation is that you are removing your form element and creating a new one upon each change and keyup event. This gets to the heart of your question about your input losing focus. The input is not losing focus; the input is being removed and replaced with a new element. The only way for the new input element to have focus is for you to directly add it via code.
As you are using jQuery and have given an ID of "foo" to your input element, you can assign it focus using:
$("#foo").focus();
However, setting focus to an element will place the cursor at the beginning of the input text and this will be painful to your user as the standard behaviour is for the cursor to remain at the end of the text; allowing the user to continue typing without first moving the cursor.
Setting the cursor position is possible via code as well. Here is a link to where the question has been asked and answered before: Use JavaScript to place cursor at end of text in text input element
The jQuery code to set the focus and set the cursor would be:
$("#foo").focus().get(0).setSelectionRange(-1, -1);
I have forked your codesandbox and added this line.
This code may work for the simplified example you have provided, but I fear it won't scale.
For example, if your form was to include even just a second text input, you would need to track which input was being changed in order to set the focus and cursor on the correct input, rather than jumping focus to the other.
I think a better solution would be to show/hide dependent parts of the form on change events rather than to replace the entire form on every change and keyup event.

How to remove the placeholder once set value in JavaScript

I'm unable to remove the placeholder after set the user name.
Anyone have idea how to remove place holder once set user name by using console
Link : https://login.microsoftonline.com
document.getElementById("i0116").value = "singapore#mail.com"
The trick is, Microsoft didn't used native HTML placeholder. They have added extra div for placeholder. You just need to hide that div after setting the value. Please see following code
document.getElementById("i0116").value = "singapore#mail.com";
document.getElementsByClassName("phholder")[0].style.display = "none";
Modified:
Microsoft is using Knockout for data binding. That's why you need to fire change event to set the values in ViewModel. Use following code after above two lines.
var event = new Event('change');
document.getElementById("i0116").dispatchEvent(event)

Stop custom datatables search box from loosing focus

I'm trying to customize the datatables search box in order to better integrate it into a bootstrap based UI. I have a table-controlbar 'horicontal_group' that contains other controls where I'd like to put the search box. It works as far as I can generate filtering events, however there is one very annoying problem:
the search box is loosing focus, every time the filter function is called.
This is a stopgap since I'd like typeahead functionality instead of letting the user click a button to search. I'd also implement a delay between keypresses and filter events of course, but first I have to deal with this focus issue.
This is how the dom looks like using the default 'f' option in datatable's sDom:
This is what I'd like to have:
wrapper_div.find('.dataTables_filter input')
.addClass('form-control tableview-search')
.appendTo(horicontal_group) //if this is uncommented, it works fine
.bind('keypress keyup', function(e){
datatable.fnFilter(searchTerm);
});
What I've tried so far (without any effect on the outcome):
use a freshly created input field instead of the field provided by the sDom-parameter 'f' (and delete 'f' from sDom)
use stopPropagation() on the event
unbind the events on the input field before binding the new ones
use .on('input' ..) instead of .bind('keypress keyup' ..)
append the whole dataTables_filter div to horicontal_group instead of just the input field
Ok, while writing this I've thought about it some more and I came to a solution that I'm gonna leave here. Using the built-in wrapper-div and adapting it to bootstrap instead of recreating it from scratch, solved my issues. If you have more insight on why the focus is lost I'd still be glad for your input.
I now initialize the sDom like this:
sDom: '<"row"<"col-lg-12 col-tableview-controls"f>><"row"<"col-lg-12"RlrtiS>>'
After dt is initialized I fixup the dom like this (note that I also used the merged search box from this thread: Add Bootstrap Glyphicon to Input Box:
var horicontal_group = wrapper_div.find('.dataTables_filter');
horicontal_group.addClass('input-group pull-right horicontal-group');
var merged_input = $("<div class='input-group merged'><span class='input-group-addon search-addon glyphicon glyphicon-search'></span></div>")
.appendTo(horicontal_group);
var input = horicontal_group.find('input');
input.addClass('form-control tableview-search')
.appendTo(merged_input)
.on("focus blur", function() {
$(this).prev().toggleClass("focusedInput")
});
var label = horicontal_group.find('label');
label.remove();

basic live text input without html <input>'s

I'm trying to start a project that requires that the javascript know every word that's typed in. An example of something I would try to accomplish would be that you would type 4 + 4, the interpreter on the webpage knows what you mean, and automatically puts = 8 on to the end of that line to show it's computed it, without having to submit anything or press any button.
I've looked into the element, but I don't want to reinvent the wheel or go against what the spec says. With putting a <textarea> as input on top of a canvas, the javascript on the page can only know what is in the textbox when the user submits the text. Is there anything out there that would help with this?
Thanks in advance!
To get the value of a textarea you can just access it via the DOM:
var textArea = document.getElementById("id-of-textarea");
To the textarea you can attach different eventlisteners, and in your case I would use onkeypress
textArea.onkeypress = function () {
var ta_value = textArea.value;
alert(ta_value);
}
Of course you'd have to write your own interpreter, I wouldn't recommend running eval on the input...
try adding a hidden input element and give it the focus when the page load is complete, and use the onkeyup handler to do whatever u want.

I want my input to be written leftwards

I know this is possible in javascript by using window.getSelection() method but I'm not familiar with this selection object.
Can you help me to write a code to make user's writing cursor to be always at the begining of the input string?
$('input[type="text"]')
.attr('maxlength','7')
.keyup(function(){
var sel = window.getSelection();
console.log(sel);
// need a code for here to make the cursor (caret) at the begining of the string
})
Can be done using a combo of:
dir = "rtl"
moving text box caret to 0 after every keypress
Demo: http://jsfiddle.net/FF9Tf/1/
Note: Uses hints/code from these answers.
Set cursor at a length of 14 onfocus of a textbox
define cursor position in form input field
you could always use CSS direction: rtl;
this line of code simply changes the direction of the text to Right To Left
and then u could just add the css class to your html elements using .addClass("your_class")
It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.
Edit: Try putting .addClass("your_class") outside the keyup function (although that might still not give you the best result you are looking for), check my comment below for a better way to do it.
Update: here is another way to do it
$('input[type="text"]').change(function () {
$(this).val() = $(this).split("").reverse().join("");
});
try this, it will keep the cursor blinking at the beginning of the text in the input box
$('input[type="text"]')
.attr('maxlength','7')
.attr('dir', "rtl")
.keyup(function(){
var sel = window.getSelection();
console.log(sel);
// need a code for here to make the cursor (caret) at the begining of the string
})
try the demo link
http://jsfiddle.net/hcWCQ/1/
in the eg: click on the input box and then press Shift+TAB and then start typing
not exactly what u r looking for.... but somewhere close

Categories