JavaScript function not being called on button press

Viewed 47

I have a relatively trivial problem, that has caused me to get stumped for a few hours

I am trying to get my button to call a JavaScript function that logs to console

Here is my HTML

 <!DOCTYPE html>
<html lang="en">
<head>

    <script type="text/javascript" src="script.js"></script>

    <meta charset="UTF-8">
    <title>McKinsey Prep</title>

    <div>
        <button onclick="click()">Some Button</button>
    </div>
</head>
<body>

</body>
</html>

The button here is calling the click() method in this JavaScript file

 console.log("Code has reached here")
    function click(){
     console.log("Button was clicked REEEEe")
}

The script.js file only has this function, I DO NOT want to execute code in my HTML document

When I run my index.js it prints the first print statement but the console.log in the function call does not appear on console when I click my button

NOTE

I am left clicking my index.html and pressing run to run my code.

What could be the issue?

2 Answers

Click() is a reserved name, you can't use it on a function because there is a native method on JS with that name.

Change the name of your function and try again. Here is an example

<button onclick="clicked()">Some Button</button>

 function clicked(){
 console.log("Button was clicked REEEEe")}

The name of the function, click, is the issue. click is not a reserved word in JavaScript but the name does exist elsewhere in the scope where the onclick handler runs. You have 2 options:

  1. Change the function name (doClick, for example).
  2. Qualify the function name by referring to it as window.click in the onclick handler: onclick="window.click()"

There's a much more in-depth explanation here: javascript function name cannot set as click?

Unrelated to this, but something that could confuse someone during debugging: In your example code, your <div> is inside the <head> part of the HTML page. That content should actually be in the <body> section below, like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript" src="script.js"></script>
    <meta charset="UTF-8">
    <title>McKinsey Prep</title>
</head>
<body>
    <div>
        <button onclick="doClick()">Some Button</button>
    </div>
</body>
</html>
Related