March 19, 2012

fire keyPressEvent in tinyMce

Question by MartinM

I’m customizing tinyMCE in Moodle (e-learning). I’ve added a toolbar button which sets focus into a text area and adds two dollar signs in it.
What I need is to place cursor between those signs, so that user can start typing between them.
Probably the best approach is just to press left arrow programaticlly, isn’t it? But I can’t figure out how to do that.
Here is the code:

tinyMCE.init({
mode : "textareas",
theme : "advanced",
theme_advanced_buttons1 : "mybutton,bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
plugins : 'inlinepopups',
setup : function(ed) {
    // Add a custom button
    ed.addButton('mybutton', {
        title : 'My button',
        image : 'img/example.gif',
        onclick : function() {
            ed.focus();
            ed.selection.setContent('$$');
        }
    });
}

});
Thanks

Answer by Thariama

This should do what you desire:

ed.addButton('mybutton', {
    title : 'My button',
    image : 'img/example.gif',
    onclick : function() {  
        ed.focus();
        ed.selection.setContent('$<span id="my_marker">u200b</span>$');
        var $marker = $(ed.getBody()).find('#my_marker');
        ed.selection.select($marker.get(0));
        $marker.remove();
    }
});

Answer by Starx

You can fire a keypress event using the following snippet.

var e = jQuery.Event('keypress');
e.keyCode = 37; //Left arrow keycode 
$(document).trigger(e);

Usage might be something like

onclick : function() {
    ed.focus();
    ed.selection.setContent('$$');
    var e = jQuery.Event('keypress');
    e.keyCode = 37; //Left arrow keycode 
    $(document).trigger(e);
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!