How to press a key event when a user enters this div?

I want to automatically press the down arrow when a user clicks on my content div, and here is my code that I tried

$('body').on('keypress', '.chat_txt', function(e) {
       if (e.keyCode === 13) {
            e.preventDefault();
            e.stopPropagation();
            $(this).append('\n'); 
            $(this).trigger({ type: 'keypress', which: 40});
        }
});

But, unfortunately, this code is barren.
JsFiddle https://jsfiddle.net/2q9x4xzm/

+4
source share
1 answer

Use the following

var e = $.Event('keypress');
        e.which = 40;
        $('.chat_txt').trigger(e);

Full code

    $('body').on('keypress', '.chat_txt', function(e) {
console.log(e.keyCode);
       if (e.keyCode === 13) {

            var evt = $.Event('keypress');
            evt.keyCode = 40;
            console.log(evt);
            $('.chat_txt').trigger(evt);
            e.preventDefault();
            e.stopPropagation();
        }
});

})

JSFIDDLE

+1
source

Source: https://habr.com/ru/post/1659904/


All Articles