Search code examples
javascriptangularjskeyevent

Performing 'document.execCommand' on 'delete' keyevents - AngularJS


I have created this demo plunkr to replicate the issue.

I want to apply strikeThroughcommand whenever a delete operation is performed. For example:

If user selects "Text" and press delete or backspace , it should become Test. It shouldn't get deleted. Can someone help me on

$container.bind('keydown keyup', function (e) {
    console.log(e)
    if(e.keyCode===8 || e.keyCode===46){
        $document[0].execCommand('strikeThrough', false); // line 1
        e.preventDefault();  // line 2
    }
});

I can capture the events as below but line 1 and line 2 doesn't work together. So how stop delete event and apply execCommand ?


Solution

  • You did bind "twice".

    It is not "don't work", it is "work twice".

    Fix code as following:

    $container.bind('keyup', function (e) {
        console.log(e)
        if(e.keyCode===8 || e.keyCode===46){
            $document[0].execCommand('strikeThrough', false); // line 1
            e.preventDefault();  // line 2
        }
    });
    $container.bind('keydown', function (e) {
        console.log(e)
        if(e.keyCode===8 || e.keyCode===46){
            e.preventDefault();  // line 2
        }
    });