I cannot seem to get event.target to work for an element that is nested in any sort of tag in a body element. I'm capturing JavaScript keystrokes and updating them into an array, like so:
$(document).keyup(function(event) {
// Check for human
if (event.originalEvent !== undefined)
updateEvents("keyup", event.target, $(event.target).val());
});
function updateEvents(targetEvent, targetElement, targetValue)
{
if (canUpdate)
{
var index = events.length - 1;
if (events[index].targetEvent !== undefined)
{
events[index].targetEvent = targetEvent;
events[index].targetElement = targetElement;
events[index].targetValue = targetValue;
}
}
}
Then after a button is clicked that signals the playback to begin, I update the text field to simulate live typing:
var count = 0;
$.each(events, function() {
window.setTimeout(action, 100 * count, count);
count++;
});
function action(index)
{
var targetEvent = events[index].targetEvent;
var targetElement = events[index].targetElement;
var targetValue = events[index].targetValue;
if (typeof targetEvent != "undefined")
{
if (targetEvent == "keyup")
{
// Simulate live typing.
$(targetElement).val(targetValue);
// Retain cursor position and user viewpoint in text fields and textareas.
var length = $(targetElement).val().length;
targetElement.setSelectionRange(length, length);
targetElement.scrollLeft = targetElement.scrollWidth;
targetElement.scrollTop = targetElement.scrollHeight;
$(targetElement).keyup();
}
}
}
In the action() function, the targetValue is the actual value of the text field, and the targetElement is the actual text field element. This code works beautifully when the text field is just in the body tag, but nesting it within any sort of tag such as div, it doesn't work at all.
I fixed it. As it turns out there was a call where I was changing the HTML of the page, which messed up my element ID's.
Related
Using Selectize.js in an Angular 9 application for selecting multiple values. Please see links to my UI at the end
https://selectize.github.io/selectize.js/
https://github.com/selectize/selectize.js
I'm trying enable the user to edit the already selected values by simply clicking on the selected item. Selectize has the concept of Plugins by which "features can be added to Selectize without modifying the main library." I'm making use of this concept to override onMouseDown event, where I'm attempting to make the clicked item editable. I have successfully used this method to override onKeyDown to implement editing of the last selected value by clicking on backspace. Please see code pasted at the bottom. this.onKeyDown = (function() {...
https://github.com/selectize/selectize.js/blob/master/docs/plugins.md
The already selected items are shown as a layer of div elements over the underlying input. To make a selected item editable, I'm removing the selected element div from the DOM, populating the underlying input element with the text from the div. That way that particular item becomes a input from a div and is editable.
There are a few issues im running into:
Its not possible to determine the caret position from the div that was clicked. I am able to get the div text and pre-populate the input element but not put the caret at the right place in input. By default the caret shows at the end and the user can move it around.
Corer cases around when a name is already being edited and the user clicks on another item to edit. The selectize library is giving api to insert selections only at the end of the already selected items. For me to keep deleting the div's and populating the input to mimic the editing effect I need to be able to insert at different positions but the library doesnt seem to have the capability for it.
Trying to see if anyone has worked on something similar or has any suggestions. Thanks in advance!
var Selectize = require('./selectize-standalone');
(function () {
Selectize.define('break_on_backspace_custom_plugin', function(options) {
var self = this;
options.text = options.text || function(option) {
return option[this.settings.labelField];
};
this.onMouseDown = (function() {
var original = self.onMouseDown;
return function(e) {
var index, option;
if (!this.$control_input.val().length && this.$activeItems.length > 0) {
index = this.caretPos - 1;
var toBeEdited = this.$activeItems[0];
var toBeEditedText = toBeEdited.textContent;
var text = toBeEditedText.substring(0, toBeEditedText.length - 1);
var prevEdit = localStorage.getItem("currentEdit");
if (index >= 0 && index < this.items.length) {
if (this.deleteSelection(e)) {
localStorage.setItem("currentEdit", text);
this.setTextboxValue(text);
this.refreshOptions(true);
if (prevEdit && prevEdit !== text) {
this.addItem(prevEdit);
}
}
//e.preventDefault();
//return;
}
}
//e.preventDefault();
return original.apply(this, arguments);
};
})();
this.onKeyDown = (function() {
var original = self.onKeyDown;
return function(e) {
var index, option;
if (e.keyCode === 8 && this.$control_input.val() === '' && !this.$activeItems.length) {
index = this.caretPos - 1;
if (index >= 0 && index < this.items.length) {
option = this.options[this.items[index]];
if (this.deleteSelection(e)) {
//option.value = option.value.substring(0, option.value.length - 1);
this.setTextboxValue(options.text.apply(this, [option]));
this.refreshOptions(true);
}
e.preventDefault();
return;
}
}
return original.apply(this, arguments);
};
})();
});
return Selectize;
})();
Pictures of UI and work in progress
Editing last element by clicking backspace
https://i.stack.imgur.com/wULcT.png
Editing middle element by clicking on it
https://i.stack.imgur.com/U5hxd.png
I'm trying to figure out a way to automatically randomize slider positions (type range) when I come across them on a webpage (mostly on web survey forms like Qualtrics or Surveymonkey). I would like to add this slider randomization to an already-existing autofill that I demonstrated below. But first, here are a couple examples of the type of sliders I would like to automate (with CSS/HTML):
&
Currently, I'm using the following script to randomly autofill survey forms on page load (radio buttons, text fields, etc). I would like to add slider randomization in the same vein to this script:
// ==/UserScript==
(function() {
// Save a random number
var modifier = Math.floor(Math.random() * 9000000);
// Create a fake user data
var user = {
pass : modifier + "",
mail : modifier + '#Example.com'
};
// Array to save data
var save_data = [];
// Check window for tags
function check(win, tagName) {
try {
// Get tags
tagName = win.document.getElementsByTagName(tagName)
} catch (e) {
// Not found - Empty array
tagName = []
}
// For each tag
for (i = 0; i < tagName.length; i++) {
// This tag
var tag = tagName[i];
// Exclude read-only or desabled
if (tag.readOnly || tag.disabled) continue;
// Get tag values
var name = tag.name;
var type = tag.type;
var value = tag.value;
// If Check box
if ('checkbox' == type){
tag.checked = Math.random() > .5;
}
// If password
else if ('password' == type){
value = user.pass;
// Update tag value
tag.value = value;
}
// If text
else if ('text' == type) {
// If mail
if(name.match(/mail/i)){
value = user.mail;
}
// Update tag value
tag.value = value;
}
// If radio
else if ('radio' == type) {
// If data don't exist
if (!save_data[name]) {
save_data[name] = 1;
}else{
save_data[name] ++;
}
// Check it with probabilities (depending on the length)
tag.checked = Math.random() < (1 / save_data[name]);
}
// If select
else if (type.match(/^select/)){
// Set a random options
tag.selectedIndex = Math.random() * (tag.options.length - 1) + 1;
}
}
// Try to set focus to the input
if (tag) try {
tag.focus()
} catch (e) {}
}
function recursive(win) {
check(win, 'password');
check(win, 'select');
check(win, 'input');
// For each frame on page
for (var i = 0; i < win.frames.length; i++) {
// Check all frames inside
recursive(win.frames[i])
}
}
recursive(window);
}());
Since I know that sliders are of the input type range, my added code would need to start with something that looks like this:
else if ('range' == type) {
if (!save_data[name]) {
save_data[name] = 1;
}else{
save_data[name] ++;
}
tag.checked = Math.random() < (1 / save_data[name]);
}
As you can see, I am basing this code off the radio button portion of the script. Unfortunately, this doesn't seem to work, and I am currently unable to find the syntax for how to select a new slider position or initiate the movement of a slider. I assume it works differently than a clickable check box or radio button. I know that sliders have ranges generally specified in the CSS/HTML, so this will obviously need to be accoutned for. Any and all help would be absolutely wonderful. Thanks in advance.
From w3school:
Change the value of a slider control:
document.getElementById("myRange").value = "75";
Tweaked it a bit to make it random (if your input range is between 0 and 100):
document.getElementById("myRange").value = Math.floor(Math.random() * 100);
In Google docs, this function changes the selected text to black
function selectedFontColorBlack() {
// DocumentApp.getUi().alert('selectedFontColorBlack');
var sel = DocumentApp.getActiveDocument().getSelection();
var elements = sel.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Only modify elements that can be edited as text; skip images and other non-text elements.
if(element.getElement().editAsText) {
var text = element.getElement().editAsText();
// Bold the selected part of the element, or the full element if it's completely selected.
if (element.isPartial()) {
text.setForegroundColor(element.getStartOffset(), element.getEndOffsetInclusive(), "#000000");
} else {
text.setForegroundColor("#000000");
}
}
}
}
This function changes the entire paragraph in which the cursor (or selection) exists to uppercase:
function uppercaseSelected() {
// DocumentApp.getUi().alert('uppercaseSelected');
var sel = DocumentApp.getActiveDocument().getSelection();
var elements = sel.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Only modify elements that can be edited as text; skip images and other non-text elements.
if(element.getElement().editAsText) {
var text = element.getElement().editAsText();
text.setText(text.getText().toUpperCase());
}
}
}
I don't see any corresponding setText function that works on the selection's "offset", as does the setForegroundColor(Integer,Integer,String). (Both of these functions are in class Text.)
How can I change the actually selected text to uppercase, and not the entire paragraph in which the selection exists?
Thank you.
Try using the setAttributes(startOffset, endOffsetInclusive, attributes) method. Check out the documentation
[EDIT: my bad, i don't think that'll do it. I'll look a bit longer tho]
The gem hidden in the post that #Mogsdad is referring to is this: var selectedText = elementText.substring(startOffset,endOffset+1);. to be little more verbose on how this is used: you can use the string method substring on objects such as DocumentApp.getActiveDocument().getSelection().getSelectedElements()[i].getElement().editAsText().getText()
so, essentially, grab that substring, convert it to uppercase, delete the text in the range (selectedElement.getstartOffset,selectedElement.endOffsetInclusive) and insert the bolded text at selectedElement.getstartOffset
Tada! check it out:
function uppercaseSelected() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var selection = DocumentApp.getActiveDocument().getSelection();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
for (var i = 0; i < selectedElements.length; ++i) {
var selectedElement = selectedElements[i];
// Only modify elements that can be edited as text; skip images and other
// non-text elements.
var text = selectedElement.getElement().editAsText();
// Change the background color of the selected part of the element, or the
// full element if it's completely selected.
if (selectedElement.isPartial()) {
var bitoftext = text.getText().substring(selectedElement.getStartOffset(), selectedElement.getEndOffsetInclusive() + 1);
text.deleteText(selectedElement.getStartOffset(), selectedElement.getEndOffsetInclusive());
text.insertText(selectedElement.getStartOffset(), bitoftext.toUpperCase());
} else {
text.setText(text.getText().toUpperCase());
}
}
}
Started with the code from Google App script Document App get selected lines or words?, and made this almost a year ago. I'm happy if it helps you.
The "trick" is that you need to delete the original text and insert the converted text.
This script produces a menu with options for UPPER, lower and Title Case. Because of the delete / insert, handling more than one paragraph needs special attention. I've left that to you!
function onOpen() {
DocumentApp.getUi().createMenu('Change Case')
.addItem("UPPER CASE", 'toUpperCase' )
.addItem("lower case", 'toLowerCase' )
.addItem("Title Case", 'toTitleCase' )
.addToUi();
}
function toUpperCase() {
_changeCase(_toUpperCase);
}
function toLowerCase() {
_changeCase(_toLowerCase);
}
function toTitleCase() {
_changeCase(_toTitleCase);
}
function _changeCase(newCase) {
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
var ui = DocumentApp.getUi();
var report = ""; // Assume success
if (!selection) {
report = "Select text to be modified.";
}
else {
var elements = selection.getSelectedElements();
if (elements.length > 1) {
report = "Select text in one paragraph only.";
}
else {
var element = elements[0].getElement();
var startOffset = elements[0].getStartOffset(); // -1 if whole element
var endOffset = elements[0].getEndOffsetInclusive(); // -1 if whole element
var elementText = element.asText().getText(); // All text from element
// Is only part of the element selected?
if (elements[0].isPartial())
var selectedText = elementText.substring(startOffset,endOffset+1);
else
selectedText = elementText;
// Google Doc UI "word selection" (double click)
// selects trailing spaces - trim them
selectedText = selectedText.trim();
endOffset = startOffset + selectedText.length - 1;
// Convert case of selected text.
var convertedText = newCase(selectedText);
element.deleteText(startOffset, endOffset);
element.insertText(startOffset, convertedText);
}
}
if (report !== '') ui.alert( report );
}
function _toUpperCase(str) {
return str.toUpperCase();
}
function _toLowerCase(str) {
return str.toLowerCase();
}
// https://stackoverflow.com/a/196991/1677912
function _toTitleCase(str)
{
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
When I select a link (with no ids or classes) within a paragraph, I need to get the selected links href value. How do I do it in jQuery? I am using document.getSelection() method for that. But I don't see any method in document.getSelection() which returns the href value.
When I select the link by dragging the mouse, I am able to get the href value like below.
currentLink = document.getSelection().anchorNode.parentElement.href;
But when I select the link by double clicking the text, the above command will not return the href value. Please help.
Here, I wrote you a little something to get you started. It's more cross-browser than your original code:
(function(AnchorSelector, $, undefined) {
AnchorSelector.getAnchorHrefs = function(e) {
var container = '';
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var div = $('<div>');
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
div.append(sel.getRangeAt(i).cloneContents());
}
container = div;
}
} else if (document.selection) {
container = $('<div>').append(document.selection.createRange().htmlText);
}
var arr = $.map(container.find('a'), function(n, i) {
return ($(n).attr('href'));
});
if (arr.length) {
alert(arr.join(','));
}
// Note: you can check e.type to see if it was a 'dblclick' or a 'mouseup'
// you may need to employ some type of debouncing to not get two alerts
// when you double click the text
}
$(function() {
$(document)
.dblclick(AnchorSelector.getAnchorHrefs)
.mouseup(AnchorSelector.getAnchorHrefs);
});
})(window.AnchorSelector = window.AnchorSelector || {}, jQuery);
And here's a jsFiddle demo.
Assuming the cursor position in a tinymce editor is inside a paragraph.
When a user hits backspace i need to know which character will get deleted.
It is necessary to know this before the character gets removed (onKeyDown is ok, onKeyUp is too late).
How can i find out which character gets deleted on backspace (before it actually gets deleted)?
The code above doesn't take into account backspacing in the middle of a paragraph, or backspacing a whole selection. Try something like the a-tools plugin (although there are several others like it) in combination with the following event handler:
jQuery('input, textarea').keydown(function(e) {
if(e.keyCode === 8) {
var selection = jQuery(this).getSelection();
var selStart = (selection.length) ? selection.start : selection.start - 1;
var selEnd = selection.end;
alert(jQuery(this).val().slice(selStart, selEnd));
}
});
in one of my plugins i set onKeyDown
ed.onKeyDown.add(function(ed, evt) {
if (paragraph && evt.keyCode == 8 && ed.selection.isCollapsed()) {
//insert special marker char
var value = '<span id="__ircaret" class="ircaret">\u2060</span>';
ed.selection.setContent(value, {format : 'raw', no_events: 1});
// node is the dom node the caret is placed in
var node = ed.selection.getNode();
var node_content = $(node).text();
var position = node_content.search('\u2060');
// this is the character
var char_vor_cursor = position != 0 ? node_content.slice(position - 1, position) : '';
// Test for soft-hyphen
if (char_vor_cursor != '' && char_vor_cursor.charCodeAt(0) == 173) {
// correct innerHTML
var text_after_backspace = node_content.slice(0, position - 1) + '<span id="__ircaret" class="ircaret">\u2060</span>' + node_content.slice(position + 1);
node.innerHTML = text_after_backspace;
}
var caret_node = $(node).find('#__ircaret').get(0);
// select caretnode and remove
ed.selection.select(caret_node);
$(ed.getBody()).find('.ircaret').remove();
}
}