Joe Farrelly Joe Farrelly -4 years ago 76
HTML Question

Trying to create a keydown event for a certain character to highlight a specific div on my webpage

I am trying to work out how I can highlight a certain div depending on a keydown event on my keyboard for my webpage. Would be awesome if someone could help me out. Cheers.

Answer Source

If you are using jquery, the jsfiddle will help.

HTML

<div id='test'>Hello world</div>

CSS

#test {
    border: 1px solid black;
    float:left;
}
.new {
    border:4px solid red !important;
}

JS

$(function() {
  $(document).on('keydown',function() {
    if(e.which == 65 || e.which == 66) {  # 65 and 66 are ASCII for a and b in small caps
       $('#test').addClass('new');
    }
  });
  $(document).on('keyup',function() {
    $('#test').removeClass('new');
  });
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download