Onpaste / paste event not firing for table on first attempts

The Google Chrome specification is an internal application that does not require cross-browser compatibility.

See http://jsfiddle.net/spetnik/vpcyt4yv/

I have a table that I am trying to allow data to be inserted into. I made individual cells selectable as such:

<td tabindex="0">

      

I originally tried adding an onpaste event to the TD elements themselves, but that didn't work at all. So instead, I added an event to the table element and just checked that the focused element was TD and then insert data into 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 work, the event usually doesn't fire on the first try. It seems I need to either a) click a random number of times in the table (different each time), or b) change focus to another window and then return before the fire occurs. In the jsFiddle, I added a console.log () call at the very beginning of the event so that I can see exactly when the event fires in the debug panel.

See the above jsFiddle or just the result https://jsfiddle.net/spetnik/vpcyt4yv/embedded/result/

+3


source to share


1 answer


Wow. The contender appears to be CSS-select / user-select CSS! I discovered this when I noticed that pasting would only be allowed after initially clicking and dragging the mouse over the cell (which explains the accidental click - only after I clicked, until my mouse moved in the middle of the click, it didn't work). I removed this CSS and now it works. Of course now I need to find a workaround to prevent the selection, but at least I'm not confused anymore.

Edit: It looks like on a normal element (like a DIV with onpaste set by the element itself) onpaste doesn't work at all when -webkit-user-select is set to none. I have submitted a bug report here



EDIT 2: I was able to find the following workaround: If I programmatically select the contents of the cell before pressing Ctrl-V, then it will work even with -webkit-user- select None. I accomplished this by adding the following event handler (jQuery shown here) to the TD (this still doesn't work in a stand-alone DIV with the -webkit-user-select parameter set to none):

$(elem).click(function(evt){
    var selection = window.getSelection();            
    var range = document.createRange();
    range.selectNodeContents(this);
    selection.removeAllRanges();
    selection.addRange(range);
})

      

+1


source







All Articles