Get a block after pressing a key

This example shows how to get a block after pressing the enter key and manipulate it. Press enter in any text block to see the result.

Code

<!DOCTYPE html>
<html>
<head>
    <title>Redactor X</title>
    <meta charset="utf-8">

    <!-- css -->
    <link rel="stylesheet" href="/your-dist-path/redactorx.min.css" />
</head>
<body>
    <!-- element -->
    <textarea id="entry">
        <p>Content</p>
    </textarea>

    <!-- js -->
    <script src="/your-dist-path/redactorx.min.js"></script>

    <!-- call -->
    <script>
    RedactorX('#entry', {
        subscribe: {
            'block.add': function(event) {
                var instance = event.get('instance');
                if (instance.isType('paragraph')) {
                    var $block = instance.getBlock();

                    // example of manipulation of a block
                    $block.html('My text');

                    // set caret to the end
                    this.app.caret.set($block, 'end')
                }
            }
        }
    });
    </script>
</body>
</html>

Usage

The example shows how to get a block after pressing a key by setting event observation when the editor starts. Another way is to make a plugin and catch the event in it.

// plugin code
RedactorX.add('plugin', 'observe-enter', {
    subscribe: {
        'block.add': function(event) {
            this.observe(event);
        }
    },
    observe: function(event) {
        var e = event.get('e');
        var key = e.which;
        if (key === 13 && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
            var instance = this.app.block.get();
            var $block = instance.getBlock();

            // example of manipulation of a block
            $block.html('My text');

            // set caret to the end
            this.app.caret.set($block, 'end')
        }
    }
});

// run with plugin
RedactorX('#entry', {
    plugins: ['observe-enter']
});