Posted By

SmellWing on 01/08/16


Tagged

enter tab keyup


Versions (?)

Enter key press behaves like a Tab in Javascript


 / Published in: JavaScript
 

URL: http://stackoverflow.com/questions/1009808/enter-key-press-behaves-like-a-tab-in-javascript

This code makes Enter key get the behavior of the Tab Key for forms.

The shift event on the above function to go back between elements. The reason textarea is included is because we "do" want to tab into it. Also, once in, we don't want to stop the default behavior of Enter from putting in a new line.

The reason a and button allow the default action, "and" still focus on the next item, is because they don't always load another page. There can be a trigger/effect on those such as an accordion or tabbed content. So once you trigger the default behavior, and the page does its special effect, you still want to go to the next item since your trigger may have well introduced it.

  1. // Map [Enter] key to work like the [Tab] key
  2. // Daniel P. Clark 2014
  3.  
  4. // Catch the keydown for the entire document
  5. $(document).keydown(function(e) {
  6.  
  7. // Set self as the current item in focus
  8. var self = $(':focus'),
  9. // Set the form by the current item in focus
  10. form = self.parents('form:eq(0)'),
  11. focusable;
  12.  
  13. // Array of Indexable/Tab-able items
  14. focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');
  15.  
  16. function enterKey(){
  17. if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key
  18.  
  19. // If not a regular hyperlink/button/textarea
  20. if ($.inArray(self, focusable) && (!self.is('a,button'))){
  21. // Then prevent the default [Enter] key behaviour from submitting the form
  22. e.preventDefault();
  23. } // Otherwise follow the link/button as by design, or put new line in textarea
  24.  
  25. // Focus on the next item (either previous or next depending on shift)
  26. focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();
  27.  
  28. return false;
  29. }
  30. }
  31. // We need to capture the [Shift] key and check the [Enter] key either way.
  32. if (e.shiftKey) { enterKey() } else { enterKey() }
  33. });

Report this snippet  

You need to login to post a comment.