Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Target an element on hover OR focus, but not both

I'm using typeahead.js to create a simple dropdown list.

The user should be able to use the down key to scroll through suggestions, and be able to use the mouse to select a suggestion. The suggestions should be appropriately highlighted in either of these scenarios.

The problem I'm having is achieving the above without highlighting both hovered states AND when scrolling using the down/up arrows.

This can be seen clearly in the gif below.

To highlight hovered states I'm using:

.tt-suggestion:hover {
  color: #f0f0f0;
  background-color: #0097cf;
}

And to highlight elements scrolled to with down/up arrows I'm using:

.tt-cursor {
  color: #f0f0f0;
  background-color: #0097cf;
}

Note: .tt-cursor is a class that is automatically appended to the suggestion div when scrolled to, and then removed when scrolled away from.

Here's a CodePen to get a better idea of what's happening.

I'm using a rails backend, and handling most of this with Javascript & jQuery.

Edit: For clarification. I want to only highlight a suggestion when hovered OR scrolled to, instead of when hovered AND scrolled to (to avoid having more than one suggestion highlighted at one time).

like image 277
nextstep Avatar asked Oct 16 '22 07:10

nextstep


1 Answers

I think this is what you need and just remove the hover css

/* .tt-suggestion:hover {
    color: #f0f0f0;
    background-color: #0097cf;
} */

  $('div').on("mouseover",'.tt-suggestion',function(){

    $('.tt-selectable').removeClass('tt-cursor')
    $('.tt-selectable').css( "color", '')
    $('.tt-selectable').css( "background-color", '')
    $(this).css( "color", '#f0f0f0')
    $(this).css( "background-color", '#0097cf')
  })
  document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;


    if (e.keyCode == '40') {
      $('.tt-selectable').css( "color", '')
      $('.tt-selectable').css( "background-color", '')
    }
   if (e.keyCode == '38') {
      $('.tt-selectable').css( "color", '')
     $('.tt-selectable').css( "background-color", '')
  }
}
like image 146
ravi Avatar answered Oct 20 '22 04:10

ravi