2

I need to develop a calendar with event associate on some day. I make this with datePicker and look my calendar :

enter image description here

I've created some events ( 3 in total ) and the color on days 1, 2 and 3 are day with event !; when I click on a day with an event, it displays the event info into a specific div.

All is ok, that work, BUT when I click on a day with element, my div with color for event disappear.

Check my code :

(function($) {
    $(document).ready(function() {

        var events = [<?php $nb = 0;
            $args = array(
                'post_type' => 'evenement',
                'posts_per_page' => -1
            );
            $loop = new WP_Query( $args );

            while ( $loop->have_posts() ) : $loop->the_post(); $nb++;
             $date = get_field('date');
             $date_info = explode("/",$date);
             $year = $date_info[2];
             $month = $date_info[0];
              $day = $date_info[1];
              /** HACK TO GET GOOD DAY / MONTH FORMAT todo: optimise it */
               if($day == "01"): $day = '1'; endif;
               if($day == "02"): $day = '2'; endif;
               if($day == "03"): $day = '3'; endif;
               if($day == "04"): $day = '4'; endif;
               if($day == "05"): $day = '5'; endif;
               if($day == "06"): $day = '6'; endif;
               if($day == "07"): $day = '7'; endif;
               if($day == "08"): $day = '8';endif;
               if($day == "09"): $day = '9';  endif;
               if($month == "01"): $month = '1'; endif;
               if($month == "02"): $month = '2'; endif;
               if($month == "03"): $month = '3'; endif;
               if($month == "04"): $month = '4'; endif;
               if($month == "05"): $month = '5'; endif;
               if($month == "06"): $month = '6'; endif;
               if($month == "07"): $month = '7'; endif;
               if($month == "08"): $month = '8';endif;
               if($month == "09"): $month = '9';  endif;
               //if($day == "0".$x): $day = $x; endif;?>{
            Title: "<?php echo get_the_title(); ?>",
            Date: new Date("<?php echo get_field('date'); ?>"),
            Lieu: "<?php echo get_field('ville'); ?>",
            Extrait: "<?php echo get_the_excerpt(); ?>",
            Type: "<?php echo get_field('type'); ?>",
            Year: "<?php echo $year; ?>",
            Month: "<?php echo $month; ?>",
            Day: "<?php echo $day; ?>"
            }<?php //if(count($nb) == $nb): ?>,<?php //endif; ?><?php endwhile; wp_reset_postdata(); ?>];

        $("#cal_content").datepicker({
            dayNamesMin: [ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam" ],
            monthNames: [ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre" ],
            nextText: "Suivant",
            prevText: "Précédent",
            //dateFormat: 'dd-mm-yy',
            beforeShowDay: function(date) {
                var result = [true, '', null];
                var matching = $.grep(events, function(event) {
                    return event.Date.valueOf() === date.valueOf();
                });

                if (matching.length) {
                    result = [true, 'highlight', null];
                }
                return result;


            },
            onSelect: function(dateText) {
                var date,
                    selectedDate = new Date(dateText),
                    i = 0,
                    event = null;

                // Determine if the user clicked an event:
                while (i < events.length && !event) {
                    date = events[i].Date;

                    if (selectedDate.valueOf() === date.valueOf()) {
                        //console.log('clicked');
                        event = events[i];
                    }else{
                        //console.log('no clicked');
                    }
                    i++;
                }
                if (event) {
                    // If the event is defined, perform some action here; show a tooltip, navigate to a URL, etc.
                    //alert(event.Title);
                    $('#cal_event_content').html(
                        '<div class="event type_'+event.Type+'">'
                            +'<span class="title">'+event.Title+'</span>'
                            +'<span class="date">'+event.Day+'/'+event.Month+'/'+event.Year+'</span>'
                            +'<span class="lieu">'+event.Lieu+'</span>'
                            +'<span class="content">'+event.Extrait+'</span>'
                            //+'day : '+event.Day
                        +'</div>'
                    );
                }
            }
        });

        $(".ui-datepicker-calendar .ui-state-default").each(function () {
            var year = $(".ui-datepicker-year").first().html();
            var nb;
            var month = $(this).parent().attr("data-month");
            var real_month = +month +1; // need this hack to get good month id ( datepicker put 9 for october per exemple )
            for (nb = 0; nb < events.length; ++nb) {
                if ( ($(this).parent().attr("data-year") == events[nb].Year) && ( real_month == events[nb].Month )  && $(this).html() == events[nb].Day) {
                    var type = events[nb].Type;
                    $(this).after('<div class="puce_color '+type+'"></div>');
                }
            }
        });

    });
})( jQuery );

When I click on a date, my puce_color disappear..

Can someone help me please ?

I would love to add multiple event per day too.. but I don't know how to do this.

Thanks so much for your help.

DaniP
  • 37,813
  • 8
  • 65
  • 74
1way
  • 60
  • 10

1 Answers1

1

The problem here is every time you select a date the calendar is "refreshed". This answer will be divided in three parts with a final demo code on Codepen:

Stop Redraw on SelectDate

With this we ensure the appended elements will remains visible on the actual calendar view, on your Select funtion set inst-inline to false:

onSelect: function(dateText, inst) {
        inst.inline = false;

Related Topic


Redraw on change Month

You also lost your appended event indicators when the month change since the events are just attached on load you can change this to run like a function everytime you change the month:

function drawEvents(fnyear, fnmonth, fnobj) {
  $('#' + fnobj).find(".ui-datepicker-calendar .ui-state-default").each(function() {
    var nb;
    for (nb = 0; nb < events.length; ++nb) {
      if ((fnyear == events[nb].Year) && (fnmonth == events[nb].Month) && $(this).html() == events[nb].Day) {
        var type = events[nb].Type;
        $(this).after('<div class="puce_color ' + type + '"></div>');
      }
    }
  });
}

Then on load run the function with the actual calendar date:

var startdate = $('#cal_content').datepicker('getDate'),
    startmonth = startdate.getMonth() + 1,              
    startyear =  startdate.getFullYear();
drawEvents(startyear,startmonth,"cal_content");

And on ChangeMonth execute the function:

onChangeMonthYear: function(year, month, widget) {
  setTimeout(function(){
    drawEvents(year, month, widget.id)
  })
}

Note:: The setTimeout function ensures the change on the actual month --- Related


CodepenDemo


Multiple Events on a Day

Check for 21/10/2016

CodepenDemo

Community
  • 1
  • 1
DaniP
  • 37,813
  • 8
  • 65
  • 74
  • thanks a lot for this ! i will try as soon as possible – 1way Oct 12 '16 at 17:30
  • hi DaniP, can i make more than 1 event / day with this solution please ? i dont think so :/ – 1way Oct 14 '16 at 08:32
  • np mate glad to help U ... just accept and upvote here to close the question cicle – DaniP Oct 14 '16 at 15:53
  • ok i'll try ! i'm newbie on this website, but i'll use everytimes ahah man, i got some work like this in my job, maybe you'll be interest to work with me on some project ? not for free ;) – 1way Oct 14 '16 at 16:00
  • i can't upvote.. not yet ;) later no prob, thanks again man, really.. you saved my life too much time – 1way Oct 14 '16 at 16:01
  • jejeje glad to help U @1way I really enjoy to help, if later require something my info is into my profile here .. have a nice day – DaniP Oct 14 '16 at 16:03
  • i sent you an email on your gmail address :) – 1way Oct 15 '16 at 17:19
  • Man, are you there ? – 1way Oct 16 '16 at 08:28