Search code examples
javascriptcssdropdownmenuitem

Adding js onclick functionality to an html menuitem dropdown menu


I am trying to add onclick functionality to a fancy drop down menu template I found so that when you make a selection from the menu, new source and alt tags are selected for an img to display different dog breeds.

The original unmodified code is here https://codepen.io/sean_codes/pen/WdzgdY and my mod attempts below. I did not include my modified ccs because it is massive and doesn't diverge that much from the original. I know menuitems have been phased out, but this configuration still seems to work for some reason across multiple browsers.

HTML

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="pets.css" />
    <script src="pets.js"></script>
</head>
<body>
    <div class="container">
        <nav class="petmenu">
            <menu>
                <menuitem>
                    <a>Pet Selection</a>
                    <menu>
                        <menuitem>
                            <a>Breed</a>
                            <menu>
                                <menuitem>
                                    <a>Dog</a>
                                    <menu>
                                        <menuitem id="german_shepherd" onclick="german_shepherd_select"><a>German Shepherd</a></menuitem>
                                        <menuitem id="golden_retriever" onclick="golden_retriever_select"><a>Golden Retriever</a></menuitem>
                                    </menu>
                                </menuitem>
                            </menu>
                        </menuitem>
                    </menu>
                </menuitem>
            </menu>
        </nav>

        <img class ="petselection" id ="pet_selection_img" src="" alt="">
    </div>

</body>
</html>

JS

// Pet Selection Commands

function german_shepherd_select() {
    document.getElementById("pet_selection_img").src = "german_shepherd.png";
    document.getElementById("pet_selection_img").alt = "This is a German Shepherd";
}

function golden_retriever_select() {
    document.getElementById("pet_selection_img").src = "golden_retiever.png";
    document.getElementById("pet_selection_img").alt = "This is a Golden Retriever";
}

Solution

  • You are just missing the () when calling the Javascript function:

     <menuitem id="german_shepherd" onclick="german_shepherd_select()">