skip to Main Content

The hover effect is not working:

function changeColor() {
  const buttonBg = document.getElementById("button-bg");
  const newColor = getRandomColor();
  buttonBg.setAttribute("fill", newColor);

  // Remove the class and re-add it to trigger the animation again
  buttonBg.classList.remove("change-color-animation");
  void buttonBg.offsetWidth; // Force reflow
  buttonBg.classList.add("change-color-animation");
}

function getRandomColor() {
  const letters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
/* CSS Styles for the button */
.svg-button {
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

.svg-button:hover {
  background-color: purple;
}

/* Animation for the button color change */
@keyframes changeColorAnimation {
  0% {
    fill: blue;
  }
  50% {
    fill: green;
  }
  100% {
    fill: red;
  }
}

.change-color-animation {
  animation: changeColorAnimation 2s infinite;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>SVG Button</title>
  </head>

  <body>
    <div class="svg-button" onclick="changeColor()">
      <!-- SVG for the button -->
      <svg width="100" height="50" xmlns="http://www.w3.org/2000/svg">
        <rect id="button-bg" x="0" y="0" width="100" height="50" fill="blue" />
        <text x="25" y="30" fill="white">Click Me</text>
      </svg>
    </div>

  </body>
</html>

HERE IS THE LINK TO MY UNADULTERATED CODE: https://github.com/Newton5000/svg-example

I tried asking AI but i was not successful.Although the colors are working in terms of changing after clicking, the hover is not working.i also got the code from AI.its only a practice so you can be sure we are only working with that button only

2

Answers


  1. A quick google looks like you have it right.
    https://css-tricks.com/change-color-of-svg-on-hover/

    Your style file has an extra s in it:

    <link rel="stylesheet" href="styles.css" />
    

    Your css file is named style.css.


    Login or Signup to reply.
  2. to change the button’s background color on hovering, you should edit your selector as this:

    .svg-button svg rect:hover {
      fill: purple;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search