Keven Wang
Keven Wang

Reputation: 1268

contenteditable div: capture input event, ignore paste event

I'm trying to build a shortcut expander, so when a user types a certain sequence of characters, it's replaced with some longer sentence.

I'm currently using 'input' event to capture contenteditable changes. The issue is, pasting also triggers the 'input' event. I only want the event to fire when user types in a character. Is there any way to do this?

Upvotes: 0

Views: 920

Answers (1)

Teemu
Teemu

Reputation: 23396

The simplest solution would be to detect a keyboard event (keydown, keyup or keypress) instead of oninput, but which to choose, depends on what the handler actually will do.

If you don't want/can't use keyboard detection, there's a back-gate. It looks like onpaste would fire before oninput (Chrome, FF). Hence you could create a flag for paste, and check it in oninput handler. Something like this:

var pasted = false,
    pad = document.getElementById('pad'); // The contenteditable
pad.addEventListener('paste', function (e) {
    pasted = true;
});
pad.addEventListener('input', function (e) {
    if (pasted) {
        pasted = false;
        return;
    }
    console.log('keyboard, cut or drop');
});

A live demo at jsFiddle.

Notice, that oninput is fired also ondrop and oncut as well as onpaste and typing in. If you don't want to handle any of these events in oninput handler, you've to listen all these events, and set a flag accordingly.

As a sidenote, IE doesn't fire oninput on contenteditables. If you want to support IEs, you need to use onkeypdown/up-onpaste-oncut-ondrop combination to achieve something similar to oninput.

Upvotes: 2

Related Questions