Search code examples
javascriptjquerycssonkeydown

revert back to unhovered css on key down


I have an element when you hover over it changes the css I have added a onkeydown function that reverts back to the original css. I was just wondering if there was anyway of getting the unhovered css with out writing it all out again?

here is my code

            $(document).keydown(function(e) {

            if (e.keyCode == 27) {
                $(NBSmegamenu).css('display', 'none');}   // esc
                $(".dynamic-children").css('border-bottom-width','none');
                $(".dynamic-children").css('border-bottom-style','none');
                $(".dynamic-children").css('border-bottom-color','none');

                $(".HoverImg").remove();
                $("span.dynamic-children").css('background-position', 'right'); 
                $("span.dynamic-children").css('background-image', 'url("/Style%20Library/NBSImages/NBS_MegaMenuDownArrowRed.png")');
                $("span.dynamic-children").css('background-repeat', 'no-repeat');
                $(".NBSDirectoryDivLine").css('border','none');

}); 

Solution

  • You'd better use classes:

    $(document).keydown(function(e) {
         if (e.keyCode == 27) 
           $(element).addClass(keyDownCssClass);
    });
    

    and you just have to remove it on key up:

    $(document).keyup(function(e) {
         if (e.keyCode == 27) 
           $(element).removeClass(keyDownCssClass);
    });