Jeffrey Yourman
Jeffrey Yourman

Reputation: 101

Prevent on click function from firing multiple times

I am trying to just make a simple click function but when I do it, it fires the exact amount of times of how many items are in the array. So if I click the button I display it fires off 3 times because there's 3 items in the array (lakers, cavs, suns). My question is how do I prevent it from firing off that x number times?

var TeamPlayers = [{
  team: 'Lakers',
  Players: ['Russell', 'Clarkson', 'Ingram', 'Randle', 'Zubacs']
}, {
  team: 'Cavs',
  Players: ['Irving', 'Smith', 'LeBron', 'Love', 'Thompson']
}, {
  team: 'Suns',
  Players: ['Ulis', 'Booker', 'Warren', 'Chriss', 'Len']
}]

for (var i = 0; i < TeamPlayers.length; i++) {
  var TeamPlayersVar = TeamPlayers[i].team
  // console.log('outside loop',TeamPlayers[i].team);

  $('.leftPlayer').append('<button class="leftButtons">' + TeamPlayers[i].team + '</button>' + '<br>')
  $(document).on('click', '.leftButtons', function(){
    console.log(this)
  });
}

Upvotes: 0

Views: 524

Answers (3)

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

You only need to place your click handler code outside the loop i.e.

var TeamPlayers = [{
  team: 'Lakers',
  Players: ['Russell', 'Clarkson', 'Ingram', 'Randle', 'Zubacs']
}, {
  team: 'Cavs',
  Players: ['Irving', 'Smith', 'LeBron', 'Love', 'Thompson']
}, {
  team: 'Suns',
  Players: ['Ulis', 'Booker', 'Warren', 'Chriss', 'Len']
}]

for (var i = 0; i < TeamPlayers.length; i++) {
  var TeamPlayersVar = TeamPlayers[i].team
  // console.log('outside loop',TeamPlayers[i].team);

  $('.leftPlayer').append('<button class="leftButtons">' + TeamPlayers[i].team + '</button>' + '<br>')
}//for()


$(document).on('click', '.leftButtons', function(){
  console.log(this)
});

Upvotes: 0

Summy
Summy

Reputation: 533

This is happening because you are assigning on click listener to a class and there are 3 elements with the specified class name, in order to make it work only one time, please use ID or use unique class names

Upvotes: 0

A Paul
A Paul

Reputation: 8251

I will suggest to use a id to do it . That should fix your issue. as the click will be registered with the id

for (var i = 0; i < TeamPlayers.length; i++) {
  var TeamPlayersVar = TeamPlayers[i].team
  // console.log('outside loop',TeamPlayers[i].team);

  $('.leftPlayer').append('<button id="btn'+i+'" class="leftButtons">' + TeamPlayers[i].team + '</button>' + '<br>')
  $("#btn"+i).click(function(){
    console.log(this)
  });
}

Upvotes: 1

Related Questions