Earth_swp
Earth_swp

Reputation: 31

Call js method in html

I have a problem with class in js and how to call it in html file.

class SetProp(){
  constructor(height,width){
    this.height = height;
    this.width = width;
  }
  function getHeight(){
    return this.height;
  }
  function getWidth(){
    return this.width;
  }
}
<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>
    <script src="TryClass.js" type="text/javascript">
      prop = new SetProp(1000,1000);
    </script>
  </head>
  <body>
    <h1>Hello</h1>
    <canvas id="canvas" width="prop.getWidth() " height="prop.getHeight();" style="border:1px solid #000000"></canvas>
  </body>
</html>

I want to make canvas with 1000*1000 by using this method. And need to pratices about using class.

Upvotes: 1

Views: 111

Answers (2)

farhadamjady
farhadamjady

Reputation: 982

your getHeight() and getWidth() functions are private and dont asign to main class prototype so if you want access them you should use main class prototype like this:

'class SetProp(height,width){
    this.height = height;
    this.width = width;

}
 SetProp.prototype.getHeight=function(){
       return this.height;
  }
  SetProp.prototype.getWidth=function(){
       return this.width;
  }'

Upvotes: 0

Frank Odoom
Frank Odoom

Reputation: 1576

The html properties width and height cannot be assigned to functions, what you need to do is write a function that will return the width and height on button click or after DOM load modify the attributes of your element with Javascript using Selectors as shown below:

document.getElementById('canvas').style.width =prop.getWidth() ;
document.getElementById('canvas').style.height =prop.getHeight() ;

Upvotes: 2

Related Questions