1. Short answer: There is no need for the each
:
Do not use click
inside of each
... you do not need to with jQuery. It handlers collections automatically for most operations (including event handlers):
e.g.
$('.switch-cal').click(function(){
//$(this) is the calendar clicked
.... CODE HERE ....
2. Try a delegated handler:
It is often more convenient to use a single delegated event handler (attached to the nearest non-changing ancestor element, or document
if none is handy). The best feature of delegated events is that they can work on elements that do not even exist yet! :)
The run-time overhead is quite low as they only need to apply the selector to the elements in the bubble-chain. Unless you are processing 50,000 mouse operations per second the speed difference is negligible, so for mouse events, don't be put of by ridiculous claims of inefficiency (like the down-voter's ranting below). The benefits usually out-way any extra overhead. Nobody clicks 50,000 times per second!:
e.g.
$(document).on('click', '.switch-cal', function(){
//$(this) is the calendar clicked
.... CODE HERE ....
Delegated events work by listening for events (in this case click
) bubbling up the DOM to a non-changing ancestor element. It then applies the selector. It then calls the function on each matching element that caused the event.
The closer the non-changing element is to the elements in question the better, to reduce the number of tests required, but document
is your fall-back if nothing else is convenient. Do not use body
as it has problems relating to styling that means events may not fire.