0

I have several link_to tags on an ERB page styled as buttons with Bootstrap (btn class). How can I bind the Enter key to one of them?

ilovebigmacs
  • 983
  • 16
  • 28
  • it should work that way by default. I just turned off JS and tried tabbing around and pressing Enter on links on a bunch of various websites - the link was always followed. – sevenseacat Jan 04 '14 at 02:55

1 Answers1

1

I'm assuming that when you say "bind the Enter key to one of them" you mean "When the user presses Enter, they follow the link of my choice."

To accomplish this, I would put an id on the link tag you want to follow. For my example below, I will use #follow-me

Then, you're gonna need to use Javascript. Assuming you're using jQuery, something like this:

var ENTER = 13; //This is the js keycode for ENTER

function my_custom_keypress(e){
  key = e.which;
  if(key == ENTER){
    var my_target_url = $('a#follow-me').attr('href'); //Figures out where your link goes...
    window.location = my_target_url(); //...and sends the user to that URL.
  }
}

$(document).on('keydown', my_custom_keypress); //when user presses a key, triggers our fxn

If you'd actually like to trigger a click event on your target link rather than forcibly linking the user, you can slightly modify the code as follows (again, this requires jQuery):

var ENTER = 13; //This is the js keycode for ENTER

function my_custom_keypress(e){
  key = e.which;
  if(key == ENTER){
    $('a#follow-me').trigger('click');
  }
}

$(document).on('keydown', my_custom_keypress); //when user presses a key, triggers our fxn

That should do it, and good luck!

Dylan
  • 1,026
  • 1
  • 10
  • 20