javascript - Two functions on Keypress won't work (textarea) -
i have created 2 function on enter key press
- to hide show dive on enter key press
- to auto resize textarea height on enter when reached end.
here fiddle : http://jsfiddle.net/rz3f3gng/2/
$('.one').hide(); $(function() { //hide show dive on enter press , on other keys hide div $('#maincontent').on('keypress', function(e) { if (e.which == 13) { e.preventdefault(); $('.one').show(); } else { $('.one').hide(); } }); function textareaauto(o) { o.style.height = "200px"; o.style.height = (2 + o.scrollheight) + "px"; } });
.one { width: 100px; height: 30px; background: red; } textarea { overflow: hidden; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="one"> </div> <textarea id="maincontent" onkeydown="textareaauto(this)" style="overflow:hidden"> </textarea>
only 1 function seems work @ time, either hide show div or auto size textarea
.
you should never mix inline event handlers jquery handlers. use 2 jquery handlers or call function existing handler:
e.g.
$('#maincontent').on('keypress', function(e){ if (e.which == 13) { e.preventdefault(); $('.one').show(); } else{ $('.one').hide(); } textareaauto(this); });
jsfiddle: http://jsfiddle.net/trueblueaussie/rz3f3gng/3/
update
as still want enter work (see comment below), rid of e.preventdefault()
e.g.
$('#maincontent').on('keypress', function(e){ if (e.which == 13) { $('.one').show(); } else{ $('.one').hide(); } textareaauto(this); });
http://jsfiddle.net/trueblueaussie/rz3f3gng/4/
which means can reduced using toggle()
to
$('#maincontent').on('keypress', function(e){ $('.one').toggle(e.which == 13); textareaauto(this); });
Comments
Post a Comment