Search code examples
javascripthtmljqueryoopecmascript-5

Why is my child class(ES5 OOP) not running on button click?


The problem is when I click the button with id squareBtn it does not run the Square class. I select the button that creates the shape class the same way and it works just fine. I have an alert in my child square class and that isn't even running. I'm aware this is probably something dumb, but I can't find the solution so I am coming here for help so please have mercy.

class Shape {
  constructor() {
    this.div = $('<div class="position-absolute"></div>');
    this.positioning();
    $(this.div).css('background-color', allHSLAcolors[randomNumber(0, 360)]);
    $(this.div).dblclick(() => this.div.remove());
    $('#container').append(this.div);
  }
  positioning() {
    $(this.div).css('top', randomNumber(0, 400) + "px");
    $(this.div).css('left', randomNumber(0, 100) + "%");
  }
}

class Square extends Shape {
  constructor() {
    this.length = $('#square').val();
    $(this.div).css('height', this.length + 'px');
    $(this.div).css('width', this.length + 'px');
    alert('hi');
  }
}

$('#hey').on('click', () => new Shape);
$('#squareBtn').on('click', () => new Square);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex justify-content-center">
  <button id="squareBtn" class="btn mx-1 btn-primary" for="square">Square</button>
  <input id="square" type="number" placeholder="Length">
</div>


Solution

    1. It's just new Square.
    $('#squareBtn').on('click', () => new Square);
    
    1. You need to call super in the constructor.
    class Square extends Shape {
      constructor() {
        super();
        // ...
      }
    }