5

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.

1
  • Could you post some source code ? We can help you to get this optimized, if possible.
    – dknaack
    Commented Jul 20, 2011 at 11:51

5 Answers 5

8

Use .delegate():

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

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

1
  • Thanks! Too you and every one else that suggested delegate. Commented Jul 20, 2011 at 12:04
4

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.
});
2
  • 1
    $(this) works inside the delegate handler and references the target element, no need for $(event.target). Commented Jul 20, 2011 at 11:58
  • Oops, too precise. I usually use binded functions (this always refer to my View object) so I'm used to use $(event.target). Commented Jul 20, 2011 at 12:14
2

Use "event delegation", i.e. bind the click event once, not to each individual div but to the div that surrounds your 1,000 divs. In the handler, you can retrieve the element for the div that was clicked, via the "event" object passed into your handler.

0
1

The approach is called event delegation and is as Ash explained. jQuery has a couple of methods to help here. live() and the newer delegate() http://api.jquery.com/delegate/ which is a bit more precise.

So you bind one click event to an element that is aparent of all the divs you are interested in and a click on them bubbles up the DOM to be captured by the parent. At which point you can do what you need to.

0

You might want to check this SO thread, it could be useful to you. From your post it's hard to tell, but an image map might be an option for you in this case. Using JQuery hover with HTML image map

Not the answer you're looking for? Browse other questions tagged or ask your own question.