-1

I am trying to build a calendar using this tutorial which uses backbone and the jquery FullCalendar plugin. I want to attach a click event handler to a cell(weekday view) of the calendar-this is the code I tried for testing:

$(document).ready(function()
{

 $('.fc-event-time').click(function()
{
  alert('test');
});

});

The above does not work.fc-event-time is the class associated with the cell that contains the time.Here is an image of the cell with some notes in it. image

The whole calendar is created with JS.The only HTML required is a div named calendar.Can that be the reason why the event handler cannot be attached. Look at some code to see what I am talking about:

    <script type='text/javascript' src='js/fcalendar/fullcalendar.js'></script>
    <script type="text/javascript" src="js/underscore.js"></script>
    <script type="text/javascript" src="js/backbone.js"></script>
    <script type="text/javascript" src="js/fcalendar/apllication.js"></script>
    <script type="text/javascript" src="js/fcalendar/custom_cal_code.js"></script>

    <div id='calendar'></div>

fullcalendar.js is the file the created the calendar inside div#calendar.Application.js is the backbone code(REST,render functions,models etc) which adds some functionality to the calendar and custom_cal_code.js is my code you see above-which tries to attach the event handler.Jquery dependencies are not shown above for the sake of brevity.

2 Answers2

4

Your problem is that at the point when your binding the event those elements don't yet exist in the DOM. Instead try using event delegation by binding to an existing higher level element.

For example you can use jQuery's .on

$('#calendar').on('click', '.fc-event-time', function () {
 alert('test');
});
Jack
  • 10,943
  • 13
  • 50
  • 65
  • it does not work...I do not think your code is wrong.Something else is preventing the code to work which I am trying to find what it is.I will do some jsfiddle testing...well the code in fiddle works(http://jsfiddle.net/fiddlehunt/sQfa7/2/)...so something in my scripts prevents the code from running – Dimitris Papageorgiou Feb 05 '14 at 17:27
  • it works after all...I implemented in the monthview of the calendar and it is OK.In the weekview proper class targeting must be done...something I have not achieved yet. – Dimitris Papageorgiou Feb 05 '14 at 19:20
0

Here's a vanilla JS (for reference) example of a test case for what I think you want. Jack's answer will also work perfectly well for jQuery selectors.

fiddle:

http://jsfiddle.net/x24ER/2/

code:

(function () {
  var cal = document.getElementById('cal');
  var myFn = function (e) {
    if (e.target.className === 'fc-event-time') {
      alert('clicked');
    }
  };
  cal.addEventListener('click', myFn);
})();
rjreed
  • 236
  • 2
  • 7