0

I am having difficulty to know how to fix "sayHello is not definedat HTMLButtonElement.onclick" issue.When I click on button this message is appeared in console.Can anybody help me please? I just want same working solution.

<button class="btn" onclick="sayHello()">Say Hello</button>

window.addEventListener('load',function(){

       function sayHello() {
         console.log("Hello Console!");
       }
});
1
  • What is it you're ultimately trying to accomplish here? Why is sayHello defined inside an event listener? Commented Dec 24, 2019 at 14:15

5 Answers 5

1

You use addEventListner() to attach event handlers to objects so you don't need to attach them inline (which is considered bad practice by lot of people). You can do this easily within the window load handler as you can see in my example below.

That way you can simply add a click event handler. I recommend to use querySelector() or querySelectorAll() to select the correct element(s) with css selectors.

window.addEventListener('load', function() {
  document.querySelector('.btn').addEventListener('click', function() {
    console.log("Hello Console!");
  });
});
<button class="btn">Say Hello</button>

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

Comments

0

You have placed the sayHello function with an anonymous function.

You could simply move the say hello function into a script tag and reference in the same way you currently have in the onClick button attribute and this should work fine.

There is no need for the additional add event listener call when hooking up an onClick handler for a button.

Comments

0

You have to declare the sayHello function outside the addEventListener callback.

function sayHello() {
  console.log("Hello Console!");
}
window.addEventListener('load', sayHello);
<button class="btn" onclick="sayHello()">Say Hello</button>

Comments

0

this will not work: sayHello is in a scope not accessible by the root scope

You can edit both html and js in this way:

Your html code: (note the usage of id)

<button id="foo" class="btn" >Say Hello</button>

Your js code:

window.addEventListener('load',function(){
  document.getElementById("foo").onclick=function() {
    console.log("Hello Console!");
  };  
});

You can read more here

Comments

0

Ditch the window load event and check if it works. If not than entirely use javascript for attaching click event on the button by giving it an id of btn-1 and

document.getElementById('btn-1').addEventListener('click',()=>{
    console.log("Hello Console!");
})

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.