'JavaScript get focus on element/tag and move around with cursor key

I have created an calendar application, a full page calendar, but the problem is I want that whenever the calendar page loads today date focused/selected automatically, and I can use arrow keys to move around dates. For example if I use left arrow key the previous date get focused/selected and etc.

Please give me any possible solution in JavaScript or jQuery. I used divs to separate each item of calendar.



Solution 1:[1]

Assign an id to each div. For example

<div class="calendar" id="day1"></div>
<div class="calendar" id="day2"></div>

and some javascript

var date = new date();  //GET DATE INFORMATION
var day = date.getDate(); //EXTRACT DAY OF MONTH

$(document).ready(function(){

  $('#day'+day).css("outline-style","solid"); //ADD FOCUS TO CURRENT DAY

  $('body').keyup(function(e){
    if (e.keycode == 37){  //IF LEFT ARROW
      $(".calendar").css("outline-style","none");
      day = day - 1;  
      $('#day'+day).css("outline-style","solid");
    }
    if (e.keycode == 39){  //IF RIGHT ARROW
      $(".calendar").css("outline-style","none");
      day = day + 1;
      $('#day'+day).css("outline-style","solid");
    }
  });

});

and some css

.calendar{
outline-style:none;
outline-width:1px;
outline-color:<YOUR CHOICE>;
}

This solution does not account for clicking left arrow when it is the first of the month or right arrow when it is the last of the month, but the idea is there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1