0

Okay so i have been looking on how to call a method from javascript in an onclick event in for example let's say a button, but i can't find any answers.

This is what I have:

Javascript

class SomeClassName() {
   methodName() {
     alert("test");
   }
}

html

<button type="button" onclick="methodName()">Click me</button>

Obviously I didn't expect this to work since you need to make an instance like:

Object = new SomeClassName();
Object.methodName();

But I can't figure out how to do this on an onclick event.

1
  • where would i need to declare the object? i did this at the top in my script tag but it give an error "Object.methodName is not a function" Commented Mar 4, 2020 at 17:37

1 Answer 1

2

Don't define your 'class' with parens

class SomeClassName()

additionally, if you want to call a method without instantiating it, you must make that method 'static'

class SomeClassName {
   static methodName() {
     alert("test");
   }
}
<button type="button" onclick="SomeClassName.methodName()">Click me</button>

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

1 Comment

Thanks, i figured it out i needed to declare this "Object = new SomeClassName();" after the class and then it worked

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.