0
<div class="target">

</div>

<script>
    class Shape {
        constructor (id, x, y) {
            this.id = id
            this.x = x
            this.y = y
            this.display()
        }

        display() {
            return 
            `
            <div class="square">
                <button class="square-button"></button>
            </div>
            `
        }
    }

    var square = new Shape(0, 5, 5);

    $('.target').html(square.display());
</script>

I want to add an event listener to the button that will be generated through each Shape instance. How would I go about doing this?

2 Answers 2

1

Although you can use an inline handler with minimal adjustments to your current code, they're pretty bad practice - instead, create the HTML element (not just a string), and attach the listener to it:

class Shape {
  constructor(id, x, y) {
    this.id = id
    this.x = x
    this.y = y
    this.display()
  }

  display() {
    const sq = $(`
            <div class="square">
                <button class="square-button">button</button>
            </div>
    `);
    sq.on('click', 'button', () => console.log('click'));
    return sq;
  }
}

var square = new Shape(0, 5, 5);

$('.target').append(square.display());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="target">

</div>

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

Comments

0

Use jquery document on event for example

$(document).on('click', '. square-button', handler)

function handler() {
  var $that = this; // the button which was click
  // do stuff etc...
}

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.