Search code examples
jquerycsshovermouseenter

How do I apply a hover class to my element?


I’m using jQuery 1.12. I have this class for when someone hovers over an LI element

.select-options li:hover {
  color: gray;
  background: #fff;
}

How do I use jQuery to trigger applying this class to an LI element? I have tried this

 $(".select").bind('keydown', function(event) {
    elt = $(this).find('.select-options li:hover')
    if (elt.length == 0) {
        elt = $(this).find('.select-options li:first')
    }       // if
    var next;
    switch(event.keyCode){
    // case up
    case 38:        
        break;
    case 40:
        next = $(elt).next();
      console.log($(next).text());
          $(next).trigger('mouseenter');
      break;
    }    
 });

but the $(next).trigger('mouseenter'); doesn’t seem to be working. You can check out my Fiddle here — http://jsfiddle.net/cwzjL2uw/15/ . Click the “select State” drop down and then click the down key on your keyboard to trigger the block of code above.


Solution

  • Per MDN:

    A CSS pseudo-class is a keyword added to selectors that specifies a special state of the element to be selected.

    So it is not necessarily a class applied to the element, also :hover is used in the context of a pointing device interaction (for example a mouse).

    In your case this should give you an starting point:

    Bind your li elements to the hover event in jquery:

    $(".select-options li")
    .hover(
    function(e) {
        $(this).addClass("selected");
    },
    function(e) {
        $(this).closest(".select-options").find("li.selected").removeClass("selected");
    }
    );
    
    $(".select").bind('keydown', function(event) {
    var currentElement = $(this).find(".select-options li.selected");
    if (currentElement.length == 0) {
        currentElement = $(this).find(".select-options li")[0];
        $(currentElement).addClass("selected");
        return;
    }       // if
    var nextElement;
    switch(event.keyCode){
    // case up
    case 38:
        nextElement = $(this).find(".select-options li")[($(this).find(".select-options li").index(currentElement) - 1) % $(this).find(".select-options li").length];
        break;
    case 40:
        nextElement = $(this).find(".select-options li")[($(this).find(".select-options li").index(currentElement) + 1) % $(this).find(".select-options li").length];
      break;
    }
    if(currentElement !== null) {
        $(currentElement).removeClass("selected");
    }
    if(nextElement !== null) {
        $(nextElement).addClass("selected");
    }
    

    });

    Need also to adjust your css

    .select-options li.selected {
      color: gray;
      background: #fff;
    }
    

    This is a working fiddle.

    http://jsfiddle.net/sge8g5qu/