0

Looking to use my left and right keyboard arrow to trigger a link_to.

My view page has this:

#RootDiv
  .nav-arrow
    = link_to lightbox_trip_path(@prev), class: "lbPrev" do
      <
  .nav-arrow
    = link_to lightbox_trip_path(@next), class: "lbNext" do 
      >

Here's the coffee script

$ ->
  if ($("#RootDiv").is(":visible"))
    $(document).keydown (e) ->
      if e.which == 37
        # left     
        $('a.lbLeft').trigger 'click'
      else if e.which == 39
        # right     
        $('a.lbNext').trigger 'click'
      return

I want to be able to only use these left and right arrow key when the #RootDiv is visible.

hellomello
  • 8,219
  • 39
  • 151
  • 297

1 Answers1

1

Try this:

$ ->
  if ($("#RootDiv").is(":visible"))
    $(document).keydown (e) ->
      if e.which == 37
        # left     
        $('a.lbLeft')[0].click()
      else if e.which == 39
        # right     
        $('a.lbNext')[0].click()
      return

Ref: Simulate mouse click

Fiddle

Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
  • Is there a difference between `.trigger 'click'` and `.click()`? I read somewhere that `.trigger 'click'` might be faster? Also, would it be better to do a `$(document).on, 'keydown' (e) ->` before doing a check if `:visible`? – hellomello Dec 31 '15 at 17:56
  • http://stackoverflow.com/questions/9666471/jquery-advantages-differences-in-trigger-vs-click – Pardeep Dhingra Jan 01 '16 at 08:12
  • I don't seem any benefit of doing check after `$(document).on, 'keydown' (e) ->` – Pardeep Dhingra Jan 01 '16 at 08:16