Home > Software engineering >  Change color of SVG path using select menu option ID
Change color of SVG path using select menu option ID

Time:11-08

I am trying to change the color of a svg path using the selected option on a Menu.

This is my code.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>

    <select name="color" id="color">
        <option value="blue">Blue</option>
        <option value="red">Red</option>
    </select>

        <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
        width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">

        <path id="path1" fill="#FFFFFF" stroke="#231F20" stroke-miterlimit="10" d="M291.451,51.919v202.54c0,0,164.521,119.846,140.146,0
            C407.227,134.613,291.451,51.919,291.451,51.919z"/>
        </svg>
</html>
<script type="text/javascript">

$('select id="color" option value "RED"').on("click", function() {
$('#path1').css({ fill: "#ff0000" });
});

</script>

This code used to work with a button (pressing a button changes the color), but I need it to work with a select menu option. What's the correct way of doing this?

CodePudding user response:

You actually want to listen for the change event when working with <input> and <select> elements. In the callback, you can get the selected <option>'s value in jQuery by selecting this (refers to the event.target) and using the .val() method: $(this).val()

        // you can listen for the "change" event on <select> and <input> elements
        $('#color').on("change", function () {
            // get the value from the event target
            const color = $(this).val()
            $('#path1').css({ fill: color });
        });
    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
</head>
<body>
    <select name="color" id="color">
        <option>Select color</option>
        <option value="blue">Blue</option>
        <option value="red">Red</option>
        <option value="#884ab2">Purple</option>
    </select>

    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
        <path id="path1" fill="#FFFFFF" stroke="#231F20" stroke-miterlimit="10" d="M291.451,51.919v202.54c0,0,164.521,119.846,140.146,0
                C407.227,134.613,291.451,51.919,291.451,51.919z" />
    </svg>


</body>
</html>

  • Related