Eugene Barsky
Eugene Barsky

Reputation: 6012

Adding class to hoverable element with JavaScript

I have a button, which changes its color on hover.

const btn = document.querySelector('.btn');
btn.classList.add('green-background');
.btn {
  text-decoration: none;
  background: blue;
  color: white;
  font-size: 20px;
}

.btn:hover {
  background: magenta;
  cursor: pointer;
}

.green-background {
  background: green;
}
<input class="btn" type="submit" value="Click me" />

I would like to add it the green-background class, so that the button is green in default state and on hover as well.

Upvotes: 2

Views: 157

Answers (3)

Razmik Ghookas
Razmik Ghookas

Reputation: 118

 function changeclass() {
            const btn = document.querySelector('.btn');
            if (!btn.classList.contains('green-background'))
                btn.classList.add('green-background');
            else
                btn.classList.remove('green-background');

        }

<!-- language: lang-css -->

    .btn {
      text-decoration: none;
      background: blue;
      color: white;
      font-size: 20px;
    }

    .btn:hover {
      background: magenta;
      cursor: pointer;
    }

    .green-background, .green-background:hover {
      background: green;
    }

<!-- language: lang-html -->

    <input class="btn" type="submit" value="Click me" onmouseover="changeclass()" onmouseout="changeclass()" />

you asked how to add class by java script : just add onmouseover="changeclass()" onmouseout="changeclass()" event to button and changeclass function but you can also do it by css same as the approved answer.

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36594

You can combine two selectors using , the default and the hover. See Groups of selectors on one rule for more information.

const btn = document.querySelector('.btn');
btn.classList.add('green-background');
.btn {
  text-decoration: none;
  background: blue;
  color: white;
  font-size: 20px;
}

.btn:hover {
  background: magenta;
  cursor: pointer;
}

.green-background:hover,.green-background {
  background: green;
}
<input class="btn" type="submit" value="Click me" />

Upvotes: 1

daformat
daformat

Reputation: 786

You just need to add a css rule that specifies the style for .green-background on hover, which you can do by setting styles for .green-background:hover

const btn = document.querySelector('.btn');
btn.classList.add('green-background');
.btn {
  text-decoration: none;
  background: blue;
  color: white;
  font-size: 20px;
}

.btn:hover {
  background: magenta;
  cursor: pointer;
}

.green-background, .green-background:hover {
  background: green;
}
<input class="btn" type="submit" value="Click me" />

Upvotes: 1

Related Questions