0

I can't figure out how to have a function refer to my button so that I can have my button actually do stuff when I click it. Here is my function:

this.Click = function () {
        alert('It works');
    }

Here is my button in the return statement:

<button id="button" onClick="Click()">Click me!</button>

Both of these are in a larger function. I keep getting errors about my Click() function and I don't know why!! [EDIT] I'm in a .js file, not an html file

3
  • remove the "this." and it should somewhat work, though you really need to look into event binding in general, as there's fundamentally better ways. Event attribs (and mixed-case attribs in general) are somewhat frowned upon these days. Commented Jun 16, 2021 at 21:22
  • Please show the "larger function". Note that in order to use a function in the onclick attribute, it must be defined in the global scope. Unless this is window, the function is not global. In any case, using addEventListener is almost always the better choice. Commented Jun 16, 2021 at 21:22
  • Did you read the error? And did you search for adding a click handler to buttons with Javascript? There are many tutorials on this. It appears you are guessing at the syntax. Commented Jun 16, 2021 at 21:23

3 Answers 3

1

Please visit https://www.w3schools.com/ and try stuff before asking questions at stackoverflow i got this answer under 3min there

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "It works";
}
</script>

</body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

0

Please supply more information if you can. What you have currently works

this.Click = function () {
        alert('It works');
    }
<head>
  <style>
  body{
    width:100%;
    background-color:tan;
  }
  #background{
    background-color:brown;
    padding:2%;
    border-radius:10%;
    width:10%;
    height:20%;
    margin-left:40%;
    }
    #button{
    background-color:tan;
    padding:2%;
    border-radius:10%;
    }
  </style>
</head>

<body>
  <div id="background">
    <button id="button" onClick="Click()">Click me!</button>
  </div>
</body>

Comments

0

Use this and it will work.

const $button = document.getElementById('button')
$button.onclick = function() {
  console.log('clicked');
}

If you want to use on HTML, you need to create the function Click on the js file. Should be like:

js file:

function Click() {
    console.log('clicked');
}

html file:

<button id="button" onclick="Click()">Click me!</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.