Domanda

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?

È stato utile?

Soluzione

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!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top