Using keypress to click an anchor tag

To scroll through content on my Laravel-based web app, there are arrows (anchor tags) on the left and right side of the screen.

Code

<a href="/" id="ContentLeft"><span class="fa fa-angle-left"></span></a>

<a href="/" id="ContentRight"><span class="fa fa-angle-right"></span></a>

JSFiddle

Question: I would like to click those anchors by pressing the left and right arrow key on the keyboard (keycode 37 and 39)

Internet search results: I found a piece of code for a text box and button combination that may be close to the solution, however, this does not work as there is no textbox, only an anchor tag.

<script>
$(document).ready(function(){
    $('#TextBoxId').keypress(function(e){
      if(e.keyCode==37)
      $('#buttonId').click();
    });
});
</script>

Many thanks in advance for any help!

Upvotes: 0

Views: 2677

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

I prefer the use of .which over .keyCode when jQuery is used.

Then I can't tell why it doesn't work with keypress... But it works fine with keyup.

You have to have an element to bind the event. So you can bind it to the whole document if you wish...

$(document).ready(function(){
  $(this).keyup(function(e){
    if(e.which==37){
      $('.fa-angle-left').click();
    }
    if(e.which==39){
      $('.fa-angle-right').click();
    }
  });
  
  // Just to console.log something here...
  $(".fa-angle-left").on("click",function(){
    console.log("Left clicked.");
  });
  $(".fa-angle-right").on("click",function(){
    console.log("Right clicked.");
  });
});
.arrow-leftright {
  color: dimgray;
  position: fixed;
  padding: 10px;
  vertical-align: middle;
  margin-bottom: 0;
  height: 70vh; 
  width: 25vw; 
  font-size: 60px; 
  line-height: 70vh; 
}

.arrow-leftright:focus, .arrow-leftright:hover {
  color: lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<a href="#" id="leftPicture" class="arrow-leftright" style="left: 0; text-align: left;"><span class="fa fa-angle-left"></span></a>

<a href="#" id="rightPicture" class="arrow-leftright" style="right: 0; text-align: right;"><span class="fa fa-angle-right"></span></a>

Upvotes: 1

Related Questions