简体   繁体   中英

How to add keypress event to div with 'contenteditable' attribute

Hi I have created a textarea from a div using -webkit-appearnce. Now I want to add an event to this div on key press. I try my best to do this but I am not sure where I am going wrong.

Please take a look at code and let me know what wrong in this

CSS:

#input {
    -moz-appearance: textfield;
    -webkit-appearance: textfield;
    background-color: white;
    background-color: -moz-field;
    border: 1px solid darkgray;
    box-shadow: 1px 1px 1px 0 lightgray inset;  
    font: -moz-field;
    font: -webkit-small-control;
    margin-top: 5px;
    padding: 2px 3px;
    width: 398px;    
}

HTML:

<div id="input" contenteditable>I look like an input</div>

Jquery:

$('#input').unbind().on('keypress', function(e) {
    if (e.which == 13) {
        alert('hello');
    }
});

Thanks

Have a look following snippet.

 $('#input').on('keypress', function(e) { alert('hello'); }); 
 #input { -moz-appearance: textfield; -webkit-appearance: textfield; background-color: white; background-color: -moz-field; border: 1px solid darkgray; box-shadow: 1px 1px 1px 0 lightgray inset; font: -moz-field; font: -webkit-small-control; margin-top: 5px; padding: 2px 3px; width: 398px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="input" contenteditable> I look like an input </div> 

Your code is working fine. Try to press enter so that it will alert . You are checking whether enter key is pressed if (e.which == 13) . You can remove that conditional statement for any key press.

Refer : JsFiddle

Your code works as intended when I try it in a JSFiddle . Your code will only run when you press Enter and it will create a new line below the existing text, as well as show the alert() . However, if what you intended was not to create a new line but only show a message when your user hits Enter , use this . If what you intended was to only greet the user once, use this . Finally if you wanted to never allow the user to write text but just show him the alert, use this .

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