Dmitry Pleshkov
Dmitry Pleshkov

Reputation: 1257

JavaScript cant find function in onclick attribute

My html:

<!doctype hmtl>
<html>
<head>
</head>
<body>
    <script type='text/javascript'>
        var playerId = 1;
        function event(action) {
            let req = new XMLHttpRequest('/act?id='+String(playerId)+'&action='+action);
            alert(action);
        }
    </script>
    <img src="up.png" width='100' height='100' onclick='event("up");'>
    <img src="down.png" width='100' height='100' onclick='event("down");'>
    <img src="left.png" width='100' height='100' onclick='event("left");'>
    <img src="right.png" width='100' height='100' onclick='event("right");'>
    <img src="fire.png" width='100' height='100' onclick='event("fire");'>
</body>
</html>

I know for sure the image is clickable. But why does the error message say event is not a function? I need help.

Upvotes: 0

Views: 1088

Answers (1)

Pedro Rodrigues
Pedro Rodrigues

Reputation: 1678

This way, you are trying to access the global object window.event, so just rename your function.

Your own code, renaming the function event to test:

<!doctype hmtl>
<html>
<head>
</head>
<body>
    <script type='text/javascript'>
        var playerId = 1;
        function test(action) {
            let req = new XMLHttpRequest('/act?id='+String(playerId)+'&action='+action);
            alert(action);
        }
    </script>
    <img src="up.png" width='100' height='100' onclick='test("up");'>
    <img src="down.png" width='100' height='100' onclick='test("down");'>
    <img src="left.png" width='100' height='100' onclick='test("left");'>
    <img src="right.png" width='100' height='100' onclick='test("right");'>
    <img src="fire.png" width='100' height='100' onclick='test("fire");'>
</body>
</html>

Upvotes: 3

Related Questions