stackow101 stackow101 - 6 months ago 8
Javascript Question

why keypress event is not worked?

please help solve the problem. i make template, view and run them.

html:

<div class="space" id="space"></div>


tpl:

<script type="text/template" id="spaceTpl">
<div class="container main_container">
<div class="row">
gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>gfdgdfgdfg<br>
</div>
</div>
</script>


view:

window.APP = window.APP || {};
APP.SpaceView = Backbone.View.extend({

initialize: function() {
this.render();
},

template: _.template($('#spaceTpl').html()),

render: function() {
this.$el.html(this.template());
return this;
},

events: {
'click': 'move',
'keypress': 'move',
'keydown': 'move'
},

move: function(e) { console.log(222)
var code = e.keyCode || e.which;

if (code === 13) {
console.log('sdsd');
}
}

});


init:

var app = new APP.SpaceView({el: '#space'});


needed after press any key in console display '222'. but nothing happens.

i.e. keypress-handler is not worked. why??

https://jsfiddle.net/9t1cwfrv/16/

Answer

It works if you set it to use on a focused element. If you don't want to focus you can use it on body element or document.

Demo: https://jsfiddle.net/9t1cwfrv/21/

Comments