Reputation: 25
I'm working on an implementation of FullCalendar by Adam Shaw (http://arshaw.com/fullcalendar/).
Each user has their own personal calendar which loads by default via JSON:
$('#calendar').fullCalendar({
header: {
left: false,
center: 'title',
right: false
},
editable: false,
events: 'http://WEBSERVER.com/calendar/json/<?=$gid?>'
});
(calendar/json/ is a PHP file that generates JSON from MySQL query results)
However, there are also shared calendars. The available calendars are shown as a list of buttons as follows:
<div class="btn-group" id="cal-lists">
<div class="btn btn-large" id="1">John's Personal Calendar</div>
<div class="btn btn-large add-cal" id="2">Company Calendar</div>
<div class="btn btn-large add-cal" id="3">Confrence Room Calendar</div>
</div>
I then have the following jQuery that is supposed to leverage the FullCalendar addEventSource method.
$("div.add-cal").click(function()
{
var json = 'http://WEBSERVER.com/calendar/json/';
var cal = $(this).attr('id');
var src = json+cal;
$('#calendar').fullCalendar( 'addEventSource', src);
$(this).removeClass('add-cal');
$(this).addClass('rem-cal');
});
$("div.rem-cal").click(function()
{
var json = 'http://WEBSERVER.com/calendar/json/';
var cal = $(this).attr('id');
var src = json+cal;
$('#calendar').fullCalendar( 'removeEventSource', src);
$(this).removeClass('rem-cal');
$(this).addClass('add-cal');
});
So whenever the user clicks
<div class="btn btn-large add-cal" id="2">Company Calendar</div>
$("div.add-cal").click(function() should be called, which adds the resource, then changes the CSS class from "add-cal" to "rem-cal".
Then, if that button is clicked again, $("div.rem-cal").click(function() should be called. This is not the case.
Clicking Company Calendar continuously adds the Company Calendar events to the display.
The first time it is clicked, the class changes to "rem-cal" appropriately, but doesn't change after that. So if the user clicks it three times, there are three instances of the events shown.
I am not very good with jQuery / JavaScript, so any advice is greatly appreciated.
Thanks in advance.
Upvotes: 0
Views: 428
Reputation: 21466
This is happening because you are binding an event handler to a selector that does not yet match anything.
You need to use jQuery's .on()
method instead.
e.g.
$("div.btn-group")
.on("click", "div.add-cal", function() {
...
})
.on("click", "div.rem-cal", function() {
...
});
Upvotes: 1