Combining click and enter function to shorten the code
Hi,
I need to trigger the same event handler on both Click and also on Enter. To do this I write this code:
- var showHideBtn = $('.js-showHidePassword');
- var showHideSpan = $(showHideBtn).children().last();
- var $pwd = $('.engage-password__field');
- // On Click
- $(showHideBtn).on('click', function(e) {
- $(showHideBtn).toggleClass('toggleShowHide');
- showHideSpan.text($(showHideBtn).is('.toggleShowHide') ? 'Hide' : 'Show');
- if ($pwd.attr('type') === 'password') {
- $pwd.attr('type', 'text');
- } else {
- $pwd.attr('type', 'password');
- }
- e.preventDefault();
- });
- // On Enter Key
- $('.js-showHidePassword').keypress(function(event) {
- var key = event.which;
- if (key == 13) // the enter key code
- {
- $(showHideBtn).toggleClass('toggleShowHide');
- showHideSpan.text($(showHideBtn).is('.toggleShowHide') ? 'Hide' : 'Show');
- if ($pwd.attr('type') === 'password') {
- $pwd.attr('type', 'text');
- } else {
- $pwd.attr('type', 'password');
- }
- e.preventDefault();
- }
- });
But again I repeat a whole bunch of code inside the both functions. How can I reduce the code and make this shorter?
Thanks