Niels Van Steen
Niels Van Steen

Reputation: 308

Call a javascript method in a class from a html button

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.

Upvotes: 0

Views: 1793

Answers (1)

Kyle
Kyle

Reputation: 1503

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>

Upvotes: 2

Related Questions