Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click event on 1000 divs, optimize approach?

I'm building a system for selling tickets to events. Right now there are about 1000 diffrent seats to choose from as a visitor. Maby one day it will be up to 5000.

Right now I have a div for each spot and then some jQuery to reserv the spot with ajax. So that meens that I have about 1000 divs and more alarming my jQuery selector sets a click event on each div.

Is there a better approach on this?

I want to trigger ajax when a div is pressed, not reloading the page.

like image 394
Johan Davidsson Avatar asked Jul 20 '11 11:07

Johan Davidsson


2 Answers

Use .delegate():

$("#container").delegate(".child", "click", function(){
    alert("Clicked!");
});

This way you'll make just one event that manages all the divs.

like image 79
Tatu Ulmanen Avatar answered Oct 04 '22 03:10

Tatu Ulmanen


simply use jQuery delegation method:

$('.theater').delegate('.seat','click',function(event){
  var self = $(event.target);
  console.log(self);
  // self is the '.seat' element that has been clicked.
});
like image 30
Pier Paolo Ramon Avatar answered Oct 04 '22 03:10

Pier Paolo Ramon