0

I have 6 'like' buttons, clicking on which, counter increase. How can i use event handler on all 'like' buttons. In my example only the last one is working.

constructor(model) {
        this.count = 0;

        for(let i = 0; i < 6; i++){
           this.renderInitialTodoForm();
        } 

        this.likeButton.addEventListener('click', () => {
            this.count++;
            this.likeCount.innerHTML = this.count;
        })
    }

    renderInitialTodoForm = () => {
        this.app = this.getElement('#root');
  
        this.likeButton = this.createElement('span', 'likeImg');
        this.likeButton.textContent = '';

        this.likeCount = this.createElement('span', 'like');
        this.likeCount.textContent = 0;

        this.app.append( this.likeButton, this.likeCount);
    };
  • Do they have same CSS class? – Kevin M. Mansour Aug 06 '21 at 14:26
  • 1
    Please show a [mcve]. What's `this` and the various methods that are called here? If you want one listener for all buttons, you can add it to the parent and use [event delegation](https://stackoverflow.com/a/55452921/6243352) to determine which was clicked. – ggorlen Aug 06 '21 at 14:27

2 Answers2

0

You render 6 like buttons but only keep a reference to one - this.likeButton. It is set to the last button created.

Woody
  • 7,578
  • 2
  • 21
  • 25
0

I think you should add the event listener to each button inside the loop.

You can do that by either adding the code bloc to renderInitialTodoForm or directly inside the for loop.

constructor(model) {

        for(let i = 0; i < 6; i++){
           this.renderInitialTodoForm();
        } 
    
    }

    renderInitialTodoForm = () => {

        this.count = 0;

        this.app = this.getElement('#root');
  
        this.likeButton = this.createElement('span', 'likeImg');
        this.likeButton.textContent = '';
    
        this.likeButton.addEventListener('click', () => {
            this.count++;
            this.likeCount.innerHTML = this.count;
        })

        this.likeCount = this.createElement('span', 'like');
        this.likeCount.textContent = 0;

        this.app.append( this.likeButton, this.likeCount);
    };

Does this work for you?

Ikdemm
  • 1,804
  • 1
  • 11
  • 25
  • if I click on any of the buttons, then one counter increases, which is the last – Мария Шипова Aug 06 '21 at 16:13
  • I think you it's because you will end up having only one count. We should create a new one evertime we create a new button. If you look closely, you are callend append with the same attribute `this.likeCount`. I will try to fix my response so you can try again. – Ikdemm Aug 06 '21 at 16:30