简体   繁体   中英

How to use “CTRL + ENTER” as “ENTER” using Jquery

Please tell how to use Ctrl + Enter↵ as Enter↵ using Jquery. I need it for chatting application.

How to create by using div "<div id="divChatMessage" contenteditable="true"></div>')"

Follwing shows as my code

$('divChatMessage').bind('keyup',function(ev){
    if(ev.keyCode == 13 && ev.ctrlKey){
        if(document.selection && document.selection.createRange){
            this.focus();
            var range = document.selection.createRange();
            range.text = "\r\n";
            range.collapse(false);
            range.select();  
        }else if(window.getSelection){
            //i don't know what to do?
        }  
    }
})

there is a JS framework called mousetrap.js which you can use to solve your problem. you simply have to do the following.

  1. add mousetrap.js to your page.
  2. add mousetrap class to you div

    <div id="divChatMessage" class="mousetrap" contenteditable="true" ></div>

    this tells moustrap to handle ctrl + enter events generated by the div .

  3. Add this script to your page

script

var $div = $('#divChatMessage');
Mousetrap.bind('ctrl+enter', function(e) {    
    if(e.target === $div[0])
    {
        $('label').append($div.html()+'<br/>');
        $div.html('');
    }
    else{
        e.preventDefault();
    }    
});

heres a JSFiddle Demo
hint: use ctrl + enter after typing something

update: Ok, I got it now, you want the cursor to go to a new line inside the div when the user presses ctrl + enter . and when user presses only enter the message will be sent.

so, you need to bind both enter and ctrl+enter .

script

var $div = $('#divChatMessage');
Mousetrap.bind('ctrl+enter', function (e) {
    if (e.target === $div[0]) {
        $div.html($div.html() + '<br/><br/>');
        var el = $div[0];
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(el.childNodes[el.childNodes.length - 1], el.childNodes[el.childNodes.length - 1].length - 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        el.focus();
    } else {
        e.preventDefault();
    }
});
Mousetrap.bind('enter', function (e) {
    if (e.target === $div[0]) {
        $('label').append($div.html() + '<br/>');
        $div.html('');
    } else {
        e.preventDefault();
    }
});

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM