Search code examples
javascripthtmlcss

I want to make an SVG a random color every time s is hit


I managed to get the head and the color outline, two SVG files, lined up completely. But there's one problem: I wanna make the head color change to a random color every time "s" is hit. But somehow its not changing the color of the head, although getRandomColor does work;

// Function to generate a random color
function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

// Function to change the color of the path element
function changePathFillColor() {
    const pathElement = document.getElementById('path-to-change');
    if (pathElement) {
        const randomColor = getRandomColor();
        pathElement.setAttribute('fill', randomColor);
    }
}

// Listen for the 'S' key press
document.addEventListener('keydown', function(event) {
    if (event.key === 's' || event.key === 'S') {
        changePathFillColor();
    }
});

And as for the HTML code, I decided I would be getting the contents of the head color's svg file and re-organizing the code like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Character Assembly</title>
    <link rel="stylesheet" href="player.css">
</head>
<body>
    <div class="character">
        <!-- Outline SVG -->
        <div class="head">
    <svg id="svg-to-change" xmlns="http://www.w3.org/2000/svg" width="150" height="90">


              <g transform="matrix(1.0, 0.0, 0.0, 1.0, 75.0, 45.0)">
    <path d="M75.0 0.0 Q75.0 18.65 53.0 31.8 31.05 45.0 0.0 45.0 -31.05 45.0 -53.05 31.8 -75.0 18.65 -75.0 0.0 -75.0 -18.65 -53.05 -31.85 -31.05 -45.0 0.0 -45.0 31.05 -45.0 53.0 -31.85 75.0 -18.65 75.0 0.0" fill="#ffcc66" fill-rule="evenodd" stroke="none"/>
  </g>
            <image href="/svgs/head/shapes/9.svg" id="headoutline"/>
  </svg>

</div>
      <!--  <object data="body.svg" type="image/svg+xml" class="part body"></object>
        <object data="leftarms.svg" type="image/svg+xml" class="part arms"></object>
        <object data="rightarms.svg" type="image/svg+xml" class="part arms"></object>
        <object data="leftlegs.svg" type="image/svg+xml" class="part legs"></object>
        <object data="rightlegs.svg" type="image/svg+xml" class="part legs"></object>-->
    </div> 

    <script src="player.js"></script>
</body>
</html>

and here is my CSS code.

.character {
    position: relative;
    width: 200px; /* Adjust the size as needed */
    height: 400px; /* Adjust the size as needed */
}

.part {
    position: absolute;
}

.head {
    animation: float 2s ease-in-out infinite;
    position: relative;
}
.headcolor {
   z-index: 1;
   margin-top: -500px;
   position: relative; 
}

.headoutline {
   z-index: 2;
   position: relative; margin
  width: 100%; 
  height: 100%; 
}

@keyframes float {
    0%, 100% {
        transform: translateY(0); /* Starting position */
    }
    50% {
        transform: translateY(-5px); /* Float up by 10 pixels */
    }
}

My guess on why this is not working is because there are two SVG files involved and the system does not know which one to change the color of. So I was thinking I should add an ID to the exposed SVG but I have no idea on how to point at it in the JavaScript code. So what can I do to make this work?


Solution

  • Try inlining your SVG:

    function getRandomColor() {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
    
    document.addEventListener('keydown', (event) => {
        if (event.key === 's' || event.key === 'S') {
            const circle = document.getElementById('colorCircle');
            circle.setAttribute('fill', getRandomColor());
        }
    });
    body, html {
        height: 100%;
        margin: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f0f0f0;
    }
    
    svg {
        width: 100px;
        height: 100px;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>SVG Circle Color Changer</title>
    </head>
    <body>
        <svg>
            <circle id="colorCircle" cx="50" cy="50" r="50" fill="blue"></circle>
        </svg>
    </body>
    </html>