Harvs
Harvs

Reputation: 533

How add event listeners dynamically

I have some code (jQuery):

$(document).on('tap', '#category1-btn', {category : "category1"}, onlineListGen);
$(document).on('tap', '#category2-btn', {category : "category2"}, onlineListGen);
$(document).on('tap', '#category3-btn', {category : "category3"}, onlineListGen);
$(document).on('tap', '#category4-btn', {category : "category4"}, onlineListGen);
$(document).on('tap', '#category5-btn', {category : "category5"}, onlineListGen);
$(document).on('tap', '#category6-btn', {category : "category6"}, onlineListGen);

This seems to violate the DNRY rule. What's more, the number of categories is dependent on a JSON file that is read, and in future, I want to dynamically create the categoryN-btn(s) depending on the JSON file contents. AS such is there a way to do the above with either dynamically generating the event listeners or somehow doing it with classes?

Upvotes: 1

Views: 68

Answers (4)

StackSlave
StackSlave

Reputation: 10627

You could wrap one of those in a function, and just call it whenever.

var tapper = (function(){
  var c = 0;
  return function(){
    $(document).on('tap', '#category'+(++c)+'-btn', {category : 'category'+c}, onlineListGen);
    return $;
  }
})();
tapper(); tapper(); // call whenever and wherever

Upvotes: 1

Harvs
Harvs

Reputation: 533

As always the idea came to me just after I posted here.

I simply added this to my event handler function

function myFunction(){
  var category = this.id.slice(0,-4); //the slice removes the '-btn' from the ID
  myData = JSONData[category]
  //some more code that uses myData
}

and used the event listener

$(document).on('tap', '.category-btn', myFunction);

where the html for the button is

<a href="#category-1" class="category-btn" id= "category1-btn">category</a>

Upvotes: 1

Lucero
Lucero

Reputation: 60190

Assuming that you know what element type these categories are, you can add a handler which works generically (assuming a button for the element with has the #categoryX-btn ID - adjust to match your markup):

$(document).on('tap', 'button', function(ev) {
    var match = /^(category[0-9]+)-btn$/.exec(this.id);
    if (match) {
        ev.data = { category: match[1] };
        return onlineListGen.call(this, ev);
    }
    return true;
});

Not tested, but you should get the idea...

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Use a for loop :

var count = N; //N is the count of button from JSON

for(var i=0;i<count;i++){
     $(document).on('tap', '#category'+i+'-btn', {category : "category"+i}, onlineListGen);
}

Hope this helps.

Upvotes: 2

Related Questions