Combining click and enter function to shorten the code

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:

  1.       var showHideBtn = $('.js-showHidePassword');
  2.       var showHideSpan = $(showHideBtn).children().last();
  3.       var $pwd = $('.engage-password__field');

  4.       // On Click
  5.       $(showHideBtn).on('click', function(e) {
  6.         $(showHideBtn).toggleClass('toggleShowHide');
  7.         showHideSpan.text($(showHideBtn).is('.toggleShowHide') ? 'Hide' : 'Show');
  8.         if ($pwd.attr('type') === 'password') {
  9.           $pwd.attr('type', 'text');
  10.         } else {
  11.           $pwd.attr('type', 'password');
  12.         }
  13.         e.preventDefault();
  14.       });

  15.       // On Enter Key
  16.       $('.js-showHidePassword').keypress(function(event) {
  17.         var key = event.which;
  18.         if (key == 13) // the enter key code
  19.         {
  20.           $(showHideBtn).toggleClass('toggleShowHide');
  21.           showHideSpan.text($(showHideBtn).is('.toggleShowHide') ? 'Hide' : 'Show');
  22.           if ($pwd.attr('type') === 'password') {
  23.             $pwd.attr('type', 'text');
  24.           } else {
  25.             $pwd.attr('type', 'password');
  26.           }
  27.           e.preventDefault();
  28.         }
  29.       });

But again I repeat a whole bunch of code inside the both functions. How can I reduce the code and make this shorter?

Thanks