user3157259
user3157259

Reputation: 27

How to avoid multiple function call

I have click event function to create a new dom elements. Basically, every time I click a button. It allows create a new hyperlink tag.

I also want to have a functionality that if new created hyperlink clicked, I want to call different function.

Please have a look following code,

var id = 1;

$('#create').on('click', function() {
   id ++ 
   $('.players').append('<a href="#" class="new" data-id='+ id + '> ' + id + 'player</a>');

   getId() 

 });

function getId() {
   $('.new').on('click', function() {
   var id = $(this).data('id')
   alert(id);
});
}

My problem is I don't want to run getId() function everytime I clicked a button, But if I run getId() function alone, new created hyperlink won't effent that functionality.

Is anyway I can call getId() function once. and It still going to effect a new created hyperlink?

Upvotes: 0

Views: 102

Answers (3)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try to use on() for dynamic elements like,

$(function(){
    var id = 1;
    $('#create').on('click', function() {
       id ++;
       $('.players').append('<a href="#" class="new" data-id='+id+'>'+id+'player</a>');
    });

    $(document).on('click','.new', function() {
  //use ^ document or your parent element players
       var id = $(this).data('id');
       alert(id);
    });
});

Upvotes: 0

George
George

Reputation: 36784

Use delegation, then there is no need to attach the event handler function every time you append. Remove your getId() function and replace it with a delegated on() method:

var id = 1;

$('#create').on('click', function () {
    id++;
    $('.players').append('<a href="#" class="new" data-id=' + id + '> ' + id + 'player</a>');
});

$('.players').on('click', '.new', function(e) {
    e.preventDefault();
    var id = $(this).data('id')
    alert(id);
});

JSFiddle

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can use one method to use the function only for once.

function getId() {
   $('.new').one('click', function() {
   var id = $(this).data('id')
   alert(id);
});

Upvotes: 3

Related Questions