Search code examples
javascripthtmlcsspseudo-class

Creating a dynamic :hover pseudoclass throught Javascript


After looking at this question, I am wondering how to do the oposite.

I already have a main class for a button I want to create, for each button I will set a different background through myButton.style.backgroundImage. But then I need to also set up and individual background on :hover for each different button I have.

How can I access the :hover pseudoclass through Javascript to add the specific background?

Thanks in advance


Solution

  • The :hover pseudoclass is a feature of CSS.

    So in your style sheet you could add.

    .myButtonClass1:hover {background: red;}
    .myButtonClass2:hover {background: blue;}
    

    Alternatively if you really want to use javascript assuming you have jQuery available you could use

    $(".myButtonClass1").hover(
      function () {
        $(this).css("background", "red");
      },
      function () {
        $(this).css("background", "none");
      }
    );
    
    $(".myButtonClass2").hover(
      function () {
        $(this).css("background", "blue");
      },
      function () {
        $(this).css("background", "none");
      }
    );