Gabriel Ciprian Magda
Gabriel Ciprian Magda

Reputation: 49

jquery UI next prev month events

I am using jquery UI datepicker to setup a calendar of events. You can see a jsfiddle of what I've create already, here: http://jsfiddle.net/ciprianmagda/bvL5kqvf/

So I've created a string with dates that have events and when you click on a date with events it will show the events list and when you click on a day without events it will show a message that there are no events for that date.

I've created a function that takes care of this when I click on a date:

$(document).ready(function(){   
    function eventInit(){
        $('.ui-datepicker-calendar tbody tr td').click(function(){
            if($(this).hasClass('dayWithEvents')){
                $('.list-of-events').fadeIn('nornal');
                $('.no-events').fadeOut(1);
                eventInit();
            }else{
                $('.no-events').fadeIn('nornal');
                $('.list-of-events').fadeOut(1);
                eventInit();
            }
        });


    }
    eventInit();

The problem is when I change the month (in js fiddle you can use the red dots) this function doen't run anymore. So if I click on a date everything will work fine but if I change the month after that, the function won't run anymore. I've tried to create another function to run the first one:

function nextPrevInit(){
    $('.ui-datepicker-next, .ui-datepicker-prev').click(function(){
        eventInit();
    }); 
}
nextPrevInit();

but the problem with this is that it only works if I change the month. Once I click on a date and change the month again, the function won't work anymore.

So, basically what I want to do is to make the eventInit function run after the month is changed. Any ideeas? Thanks

Upvotes: 0

Views: 650

Answers (1)

T J
T J

Reputation: 43156

Modifying the code by delegating the event handlers for next and previous buttons as shown below seems to fix the issue:

function eventInit() {
  $('.ui-datepicker-calendar tbody tr td').click(function () {
    if ($(this).hasClass('dayWithEvents')) {
        $('.list-of-events').fadeIn('nornal');
        $('.no-events').fadeOut(1);

    } else {
        $('.no-events').fadeIn('nornal');
        $('.list-of-events').fadeOut(1);
    }
      eventInit();
  });
}
eventInit();
$(document).on("click", '.ui-datepicker-next, .ui-datepicker-prev', eventInit);

Updated Fiddle

Upvotes: 1

Related Questions