onpaste / paste event not firing for table on first few attempts - javascript

Google Chrome specific - this is an internal-use app that does not require cross-browser compatibility
See http://jsfiddle.net/spetnik/vpcyt4yv/
I have a table into which I am attempting to allow pasting of data. I made the individual cells selectable as such:
<td tabindex="0">
I originally tried adding the onpaste event to the TD elements themselves, but this did not work at all. So instead, I added the event to the table element and just check to make sure that the focused element is a TD and then paste the data to that element:
document.getElementById("tblData").onpaste = function(evt){
if(document.querySelector(":focus").tagName.toLowerCase() != "td"){
return;
}
document.querySelector(":focus").innerText = evt.clipboardData.getData("text/plain");
};
While this does essentially work, the event usually does not fire on the first attempt. It seems that I need to either a) click around in the table a random number of times (each time is different) or b) change focus to another window and then back again before the event fires. In the jsFiddle I have added a console.log() call to the very beginning of the event so that I can see exactly when the event fires in the debug pane.
See the above jsFiddle or just the result at https://jsfiddle.net/spetnik/vpcyt4yv/embedded/result/

Wow. The culprit seems to be the -webkit-user-select/user-select CSS! I discovered this when I noticed that pasting would be allowed only after initially clicking and dragging the mouse over a cell (which explains the random clicking - only after I clicked until my mouse moved mid-click did it work). I removed this CSS and now it works. Of course, now I need to find a workaround to prevent selecting, but at least I'm no longer stumped.
Edit: It seems that on a normal element (e.g. a DIV with the onpaste set to the element itself) onpaste does not work at all when -webkit-user-select is set to none. I submitted a bug report here
EDIT 2: I have managed to find the following workaround: If I programmatically select the contents of the cell before Ctrl-V is pressed, then it will work, even with -webkit-user-select set to none. I accomplished this by adding the following event handler (jQuery shown here) to the TD (this still does not work in a standalone DIV with -webkit-user-select set to none):
$(elem).click(function(evt){
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(this);
selection.removeAllRanges();
selection.addRange(range);
})

Related

Moving caret in the contents of a read-only div allowing for dynamic highlighting

I've been struggling with getting a field working properly. This field displays a lot of data, and the user wants to select and copy a large portion of it. The data is basically a big list and the user wants to select all entries below a certain point. The way that they achieve the selection is by highlighting a word or two in the first entry they want then pressing ctrl+shft+end to select everything to the bottom. This was working until a new feature on the page was added below the contents of the list. Now the hot key select also selects the contents of the rest of the page.
The current implementation is simply :
<div id='diff-contents'>[content here]</div>
<div id='trailing-content'>blah blah blah...</div>
I have tried a read-only input field:
<input id='diff-contents' value='[content here]' readonly/>
This works in Firefox to some extent however the contents contains HTML, and the input field show html literally, not rendered. In addition to that Chrome doesn't show a blinking caret and the hot keys do nothing, so the input field is sadly not viable for me in this situation.
How can I make a selectable field that maintains focus for the cursor and shows a blinking caret but is not editable using javascript, CSS, HTML, or JQuery?
Edit: jsfiddle example that should clarify a bit.
Look at these questions how to determine the current selection: Getting selected text in a browser, cross-platform
The next step is to create a new range which starts at the end tag of #diff-contents. With this information, you should be able to extend/modify the existing selection.
I suggest to either add a button to the UI or use JavaScript with a key-press handler to trigger this code.
With that, the correct amount of HTML should be selected. Users can then copy that into the clipboard with Ctrl+C.
#Aaron Digulla mentioned key listeners, and that got me thinking about simply stopping the events.
The diff-content element is still a div but it is set to editable. This gives both HTML rendering and a blinking caret.
$(this).keydown(function (event) {
if (document.activeElement.id == 'diff-content') {
if (!allowedKeys(event.keyCode)) {
//The only other key presses that should be processed are ctrl+c (keycode 67) and ctrl+a (65)
if (!event.ctrlKey || !(event.keyCode == 67 || event.keyCode == 65)) {
event.preventDefault();
}
}
}
});
The javascript adds a keydown event listener to the entire page. This is necessary since if you just add it to the element, the event has already propagated through the rest of the page and will still be processed, and this was causing funny issues for me. Next we check if it's the diff-content that is active since we want other input elements to still operate normally. Then we check if the key event is an allowed key (tab, home, end, arrows). And finally, check for ctrl+c and ctrl+a and allow those too. I tried event.stopPropogation() and event.stopImmediatePropogation(), and neither of those worked, but preventDefault did.
Lastly, I added style="outline-style:none" to the element so that the blue border would not appear when the element has focus.
The only issue that I have yet to resolve is that since it is editable, the browser still allows you to select and then right click to either cut or paste, which will allow you to alter the text.
Here is the final jsfiddle for what I am using: http://jsfiddle.net/wh3nzmj8/12/

How to detect rightclick + cut/delete/paste/undo in javascript?

In my JavaScript/jQuery code, I have a text field that I run an event when the text changes using the keyup event. However currently I only account for changes done using the keyboard.
Is there a way I can detect when a text field text changed because the user did a right click and clicked on cut or delete or paste or undo?
Note: This needs to work in IE9, and preferably Firefox and chrome, but definitely needs to work in IE9.
Thanks
jsFiddle Demo
Use jquery to bind an input event to the element like this:
$('#myInput').bind('input',function(){
//use this for the input element when input is made
var inputValue = this.value;//for example
});
As a start, this is not really the correct way to do it. But if you react on the mouseout event of a input you will most likely get it to behave the way you want.
$('#input').mouseout(function(){
if($('#input').is(":focus"))
console.log("Right-click");
});
Though it is to note that this might not work as well on textareas since they tend to be larger and the mouse might not be outside of it when the contextmenu has been clicked.
Note: Other than #Travis J that react to all interaction, this will (probably) only trigger an event on rightclick (and regular mouseout).

My web app non-deterministically crashes in Google Chrome

In my web app, I use Ctrl + Arrow keys to navigate from cell to cell in a table.
All cells contain a visible <span>, and a hidden <input> element -- their values are kept in sync.
When a cell is activated, the <span> is hidden, while the input is shown.
Everything works just fine in Firefox, IE, Opera, etc. Yet, when I load up Chrome, using Ctrl+Left or Ctrl+Right crashes the page (I'm seeing the "Aw Snap" page). Odd thing is, Ctrl+Up and Ctrl+Down work.
I've identified that the following code is (directly or indirectly responsible for the crashes):
/**
* Deactivates a cell, hiding its input field, and showing its span field
*/
View.prototype.deactivateCell = function (cell){
//Show the span, hide the input
var label = cell.descendants()[0];
var input = cell.descendants()[1];
if(label){
label.show();
}
if(input){
//THIS NEXT LINE IN PARTICULAR CAUSES THE CRASH
//I've also tried input.style.display = "none"; - same result
input.hide();
}
}
Odd thing is, this code is called by Ctrl+Up/Down, as well as Ctrl+Left/Right - yet it only crashes on Left/Right -- even with identical cell values!
All of these cells have two, and only two, descendants... And the crash has nothing to do with the source cells, or the destination cells -- it's possible to move into any cell from above, but not from the left.
What's even stranger; adding an alert(1); at the end of the deactivateCell(cell) method prevents the crash. Putting it at the start of the method has no effect (Other then displaying the alert dialogue, before the crash)
I've tried isolating the relevant HTML + this method in a test file - I could not reproduce the crash.
Has anyone encountered this? Should I write it off as a browser bug? Does anyone know how I might debug this, or try to fix it? I haven't the foggiest impression how my Javascript can cause the browser to caput, when so many other websites are fine.
I'm not a prototype hero, but I noticed that you call cell.descendants() without checking if cell is null or not.
Also, are you hiding the current input the cursor is in? if so, try to focus() to a different input before you hide the current one.
It turns out this is a bug with Webkit that was already filed and fixed.

jQuery bug in IE when selecting Jeditable select boxes

I'm making an intranet application and experimenting with the Jeditable plugin for jQuery. The following function makes an element (in this case a td element) clickable, which then turns it editable (again in this case selectable, as it's a select box) and checks a key listener to see if tab or shift-tab has been pressed to activate the next or previous editable area.
$('.editBool').editable(function(value, settings){
// show and hide clickable links. shouldn't be important to problem,
// but i don't know at this point
$(this).parent().find('a.editbutton').hide();
$(this).parent().find('a.savebutton').show();
$(this).parent().addClass('notSaved');
// sets a warning if they leave the page without saving edited data
window.onbeforeunload = savePage;
// needed for editable to work (apparently).
return(value);
}, {
data : "{'Yes':'Yes','No':'No'}",
type : 'select',
onblur : 'submit',
callback : function(value, settings) {
// kp is the keypress, sp is a bool checking for the shift key
if (kp == 9){if (sp){$(this).prev().click();}else{$(this).next().click();}kp = null;}
}
});
If I tab through the Jeditable boxes with code like this, I have no problems, until I move the mouse in Internet Explorer (7 and 8). If the currently selected element is a select box (using the code above), when the mouse moves, the select box loses focus and triggers the onblur event. If the mouse doesn't move, focus stays with the select box.
If I use the cursors to try to select another value, focus is lost as well, and again the onblur event is triggered.
This does not happen with any other kind of element I've set as Jeditable (textarea, autogrow textarea, masked text), just on selects, and only in IE 7-8 (maybe 6 as well, but I don't care about 6 anymore). It works as I expect it to work in FF3, Chrome 4+, Opera 10 (focus stays on select box when mouse moves and options can be selected by keyboard arrow commands).
Does anyone have any ideas about why this might be happening?
Thanks.
Clarification time: This bug only happens when using a next() function to go from a jeditable enabled td set to change to text, textedit or autogrow on click, to a jeditable enabled td set to a select box. It doesn't happen when going from text to text, or select to text.
More detail time: The bug is happening when the focus() is called in the jeditable jQuery plugin, line 253:
$(':input:visible:enabled:first', form).focus();
It seems if the mouse is moved after this line, it causes the select box to lose focus. This is driving me nuts, and as I want to solve this one, I've been attacking it every which way I can. I came across a curious oddity by swapping the previous line for this one:
setTimeout(function() { $(':input:visible:enabled:first', form).focus();}, 1000);
During the second between the select box being created and the focus set, if the mouse moves, focus is not lost once set. If the mouse does not move before focus is set, when it does move, focus is lost. This appears to be total fruit and nuttiness. I've been googleing the hell out of this issue, and can't find a solution. Any help would be very much appreciated.
Thanks,

Problem getting selected text when using a sprited button and selection.createRange() in Internet Explorer

I'm working on implementing sprited buttons in Stackoverflow's beloved WMD markdown editor and I've run into an odd bug. On all versions of IE, the selected text is lost upon button clicks, so, say, highlighting a block of text and clicking the code button acts like you placed the cursor at the end of the selection and clicked the button.
e.g. highlighting this:
This
Is
Code
and clicking the code button give you:
This
Is
Code`enter code here`
What's really weird is that I left the original non-sprited button bar in and that works just fine. In fact ALL buttons and keyboard shortcuts code use the same doClick(button) function!
Old-style non-sprited buttons: OK
Keyboard shortcuts: OK
Sprited buttons in non-IE browsers: OK
Sprited buttons in IE: WTF
I've isolated the problem down to a call to selection.createRange() which finds nothing only when the sprited button is clicked. I've tried screwing around with focus()ing and making sure as little as possible happens before the doClick() but no joy. The keyboard shortcuts seem to work because the focus is never lost from the input textarea. Can anyone think of a hack that will let me somehow collect the selected text in IE?
The onclick handler looks like this:
button.onmouseout = function(){
this.style.backgroundPosition = this.XShift + " " + normalYShift;
};
button.onclick = function() {
if (this.onmouseout) {
this.onmouseout();
}
doClick(this);
}
I've tried moving the onmouseout call to after the doClick in case that was causing a loss of focus but that's not the problem.
EDIT:
The only thing that seems to be different is that, in the original button code, you are clicking on an image. In the sprited code, you are clicking on a list item <li> with a background image set. Perhaps it's trying to select the non-existent text in my list item?
/EDIT
Actual code is located in my wmd repository on git in the button-cleanup branch.
If you revert to the 0d6d1b32bb42a6bd1d4ac4e409a19fdfe8f1ffcc commit you can see both button bars. The top one is sprited and exhibits the weird behavior. The bottom one contains the remnants of the original button bar and works fine. The suspect code is in the setInputAreaSelectionStartEnd() function in the TextareaState object.
One last thing I should mention is that, for the time being, I'm trying to keep the control in pure Javascript so I'd like to avoid fixing this with an external library like jQuery if that's possible.
Thanks for your help!
I know what the answer to my own question is.
The sprited buttons are implemented using an HTML list and CSS, where all the list items have a background image. The background image is moved around using CSS to show different buttons and states (like mouseover highlights). Standard CSS button spriting stuff.
This works fine in IE with one exception: IE tries to select the empty list text when you click on the background image "button". The selection in the input textarea goes away and the current selection (which will be returned by document.selection.createRange()) is moved to the empty text in the list item.
The fix for this is simple - I created a variable to cache the selection and a flag. In IE I cache the selection and set the flag in a mousedown event handler. In the text processing, I check for the presence of the flag - if it's set I use the cached range instead of querying document.selection.createRange().
Here are some code snippets:
wmd.ieCachedRange = null;
wmd.ieRetardedClick = false;
if(global.isIE) {
button.onmousedown = function() {
wmd.ieRetardedClick = true;
wmd.ieCachedRange = document.selection.createRange();
};
}
var range;
if(wmd.ieRetardedClick && wmd.ieCachedRange) {
range = wmd.ieCachedRange;
wmd.ieRetardedClick = false;
}
else {
range = doc.selection.createRange();
}
The solution is only a few lines of code and avoids messing around with the DOM and potentially creating layout engine issues.
Thanks for your help, Cristoph. I came up with the answer while thinking and googling about your answer.
You have to blur() a button before IE can select anything else on a page.
Can you provide a minimal example (only containing relevant code) which reproduces the bug?

Categories