On click event repeating action

Asked

Viewed 358 times

1

My code:

var calendar = {

    init: function(org_id) {

             $.ajax({
                url: 'http://localhost:8000/listar/' + org_id,
                type: 'GET',
                dataType: 'json'
            }).done(function(data) {
                var events = data.events;

                for (var i = 0; i < events.length; i++) {
                    $('.list').append('<div class="day-event" style="text-align: center;" date-day="'+
                     events[i].day +'" date-month="' +
                     events[i].month +'" date-year="'+ events[i].year +'" data-number="'+ 
                     i +'"><h4>' + events[i].orgao + '</h4><h2 class="title">'+
                      events[i].title +'</h2><p>Das ' + events[i].inicio + ' ás ' + events[i].fim +
                     '</p><p>'+ events[i].description +'</p></div>');
                }

                // start calendar
                calendar.startCalendar();

            }).fail(function(data) {
                    console.log(data);
                });


    },

    startCalendar: function() {
        var mon = 'Seg';
        var tue = 'Ter';
        var wed = 'Qua';
        var thur = 'Qui';
        var fri = 'Sex';
        var sat = 'Sab';
        var sund = 'Dom';

        /**
         * Get current date
         */
        var d = new Date();     
        var yearNumber = (new Date).getFullYear();
        var strDate = yearNumber + "/" + (d.getMonth() + 1) + "/" + d.getDate();


        // custom
        var tmpDate = new Date(strDate);
        var firstDay = tmpDate.getDay();
        var firstDisplay = true;


        var monthNumber = d.getMonth() + 1;


        function GetMonthName(monthNumber) {
            var months = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
            return months[monthNumber - 1];
        }

        setMonth(monthNumber, mon, tue, wed, thur, fri, sat, sund);

        function setMonth(monthNumber, mon, tue, wed, thur, fri, sat, sund) {
            $('.month').text(GetMonthName(monthNumber) + ' ' + yearNumber);
            $('.month').attr('data-month', monthNumber);
            printDateNumber(monthNumber, mon, tue, wed, thur, fri, sat, sund);
        }




        $('.btn-next').on('click', function(e) {            
            var monthNumber = $('.month').attr('data-month');
            console.log(monthNumber);
            if (monthNumber > 11) {
                $('.month').attr('data-month', '0');
                var monthNumber = $('.month').attr('data-month');
                yearNumber = yearNumber + 1;
                setMonth(parseInt(monthNumber) + 1, mon, tue, wed, thur, fri, sat, sund);
            } else {
                setMonth(parseInt(monthNumber) + 1, mon, tue, wed, thur, fri, sat, sund);
            };
        });


        $('.btn-prev').on('click', function(e) {            
            var monthNumber = $('.month').attr('data-month');
            if (monthNumber < 2) {
                $('.month').attr('data-month', '13');
                var monthNumber = $('.month').attr('data-month');
                yearNumber = yearNumber - 1;
                setMonth(parseInt(monthNumber) - 1, mon, tue, wed, thur, fri, sat, sund);
            } else {
                setMonth(parseInt(monthNumber) - 1, mon, tue, wed, thur, fri, sat, sund);
            };
        });





        /**
         * Get all dates for current month
         */

        function printDateNumber(monthNumber, mon, tue, wed, thur, fri, sat, sund) {

            tmpDate = new Date(yearNumber, monthNumber - 1, 1);
            firstDay = tmpDate.getDay() - 1;

            $($('tbody.event-calendar tr')).each(function(index) {
                $(this).empty();
            });

            $($('thead.event-days tr')).each(function(index) {
                $(this).empty();
            });

            function getDaysInMonth(month, year) {
                var date = new Date(year, month, 1);
                var days = [];
                while (date.getMonth() === month) {
                    var tmpArr = [];
                    tmpArr[0] = date.getDate();
                    tmpArr[1] = date.getDay();
                    days.push(tmpArr);              
                    date.setDate(date.getDate() + 1);
                }   

                return days;
            }

            // function getDaysInMonth(month, year) {
            //  // Since no month has fewer than 28 days
            //  var date = new Date(year, month, 1);
            //  var days = [];
            //  while (date.getMonth() === month) {
            //      days.push(new Date(date));
            //      date.setDate(date.getDate() + 1);
            //  }
            //  return days;
            // }

            i = 0;

            setDaysInOrder(mon, tue, wed, thur, fri, sat, sund);

            function setDaysInOrder(mon, tue, wed, thur, fri, sat, sund) {
                firstDisplay = true;
                var monthDay = getDaysInMonth(monthNumber - 1, yearNumber)[0].toString().substring(0, 3);
                $('thead.event-days tr').append('<td>' + sund + '</td><td>' + mon + '</td><td>' + tue + '</td><td>' + wed + '</td><td>' + thur + '</td><td>' + fri + '</td><td>' + sat + '</td>');
            };


            $(getDaysInMonth(monthNumber - 1, yearNumber)).each(function(index) {
                var day = $(this)[0];
                var week = $(this)[1];
                var index = index + 1;


                if(firstDisplay == true){
                    for (var i = 0; i <= firstDay; i++) {
                        $('tbody.event-calendar tr.1').append('<td date-month="' + '' + '" date-day="' + '' + '" date-year="' + '' + '"><a href="#">' + '' + '</a></td>');
                    };
                    firstDisplay = false;
                }

                $('tbody.event-calendar tr.1').append('<td date-month="' + monthNumber + '" date-day="' + index + '" date-year="' + yearNumber + '"><a href="#">' + index + '</a></td>');
            });


            // function setDaysInOrder(mon, tue, wed, thur, fri, sat, sund) {
            //  var monthDay = getDaysInMonth(monthNumber - 1, yearNumber)[0].toString().substring(0, 3);
            //  console.log('===' + monthDay);
            //  if (monthDay === 'Mon') {
            //      $('thead.event-days tr').append('<td>' + mon + '</td><td>' + tue + '</td><td>' + wed + '</td><td>' + thur + '</td><td>' + fri + '</td><td>' + sat + '</td><td>' + sund + '</td>');
            //  } else if (monthDay === 'Tue') {
            //      $('thead.event-days tr').append('<td>' + tue + '</td><td>' + wed + '</td><td>' + thur + '</td><td>' + fri + '</td><td>' + sat + '</td><td>' + sund + '</td><td>' + mon + '</td>');
            //  } else if (monthDay === 'Wed') {
            //      $('thead.event-days tr').append('<td>' + wed + '</td><td>' + thur + '</td><td>' + fri + '</td><td>' + sat + '</td><td>' + sund + '</td><td>' + mon + '</td><td>' + tue + '</td>');
            //  } else if (monthDay === 'Thu') {
            //      $('thead.event-days tr').append('<td>' + thur + '</td><td>' + fri + '</td><td>' + sat + '</td><td>' + sund + '</td><td>' + mon + '</td><td>' + tue + '</td><td>' + wed + '</td>');
            //  } else if (monthDay === 'Fri') {
            //      $('thead.event-days tr').append('<td>' + fri + '</td><td>' + sat + '</td><td>' + sund + '</td><td>' + mon + '</td><td>' + tue + '</td><td>' + wed + '</td><td>' + thur + '</td>');
            //  } else if (monthDay === 'Sat') {
            //      $('thead.event-days tr').append('<td>' + sat + '</td><td>' + sund + '</td><td>' + mon + '</td><td>' + tue + '</td><td>' + wed + '</td><td>' + thur + '</td><td>' + fri + '</td>');
            //  } else if (monthDay === 'Sun') {
            //      $('thead.event-days tr').append('<td>' + sund + '</td><td>' + mon + '</td><td>' + tue + '</td><td>' + wed + '</td><td>' + thur + '</td><td>' + fri + '</td><td>' + sat + '</td>');
            //  }
            // };


            // $(getDaysInMonth(monthNumber - 1, yearNumber)).each(function(index) {
            //  var index = index + 1;
            //  if (index < 8) {
            //      $('tbody.event-calendar tr.1').append('<td date-month="' + monthNumber + '" date-day="' + index + '" date-year="' + yearNumber + '">' + index + '</td>');
            //  } else if (index < 15) {
            //      $('tbody.event-calendar tr.2').append('<td date-month="' + monthNumber + '" date-day="' + index + '" date-year="' + yearNumber + '">' + index + '</td>');
            //  } else if (index < 22) {
            //      $('tbody.event-calendar tr.3').append('<td date-month="' + monthNumber + '" date-day="' + index + '" date-year="' + yearNumber + '">' + index + '</td>');
            //  } else if (index < 29) {
            //      $('tbody.event-calendar tr.4').append('<td date-month="' + monthNumber + '" date-day="' + index + '" date-year="' + yearNumber + '">' + index + '</td>');
            //  } else if (index < 32) {
            //      $('tbody.event-calendar tr.5').append('<td date-month="' + monthNumber + '" date-day="' + index + '" date-year="' + yearNumber + '">' + index + '</td>');
            //  }
            //  i++;
            // });


            var date = new Date();
            var month = date.getMonth() + 1;
            var thisyear = new Date().getFullYear();
            setCurrentDay(month, thisyear);
            setEvent();
            displayEvent();         
        }

        /**
         * Get current day and set as '.current-day'
         */
        function setCurrentDay(month, year) {
            var viewMonth = $('.month').attr('data-month');
            var eventYear = $('.event-days').attr('date-year');
            if (parseInt(year) === yearNumber) {
                if (parseInt(month) === parseInt(viewMonth)) {
                    $('tbody.event-calendar td[date-day="' + d.getDate() + '"]').addClass('current-day');
                }
            }
        };

        /**
         * Add class '.active' on calendar date
         */
        $('tbody td').on('click', function(e) {
            if ($(this).hasClass('event')) {
                $('tbody.event-calendar td').removeClass('active');
                $(this).addClass('active');
            } else {
                $('tbody.event-calendar td').removeClass('active');
            };
        });

        /**
         * Add '.event' class to all days that has an event
         */
        function setEvent() {           
            $('.day-event').each(function(i) {
                var eventMonth = $(this).attr('date-month');
                var eventDay = $(this).attr('date-day');
                var eventYear = $(this).attr('date-year');
                var eventClass = $(this).attr('event-class');
                if (eventClass === undefined) eventClass = 'event';
                else eventClass = 'event ' + eventClass;

                if (parseInt(eventYear) === yearNumber) {
                    $('tbody.event-calendar tr td[date-month="' + eventMonth + '"][date-day="' + eventDay + '"]').addClass(eventClass);
                }
            });
        };

        /**
         * Get current day on click in calendar
         * and find day-event to display
         */
        function displayEvent() {           
            $('tbody.event-calendar td').on('click', function(e) {              
                $('.day-event').slideUp('fast');
                var monthEvent = $(this).attr('date-month');
                var dayEvent = $(this).text();
                $('.day-event[date-month="' + monthEvent + '"][date-day="' + dayEvent + '"]').slideDown('fast');
            });
        };

        /**
         * Close day-event
         */
        $('.close').on('click', function(e) {
            $(this).parent().slideUp('fast');
        });

        /**
         * Save & Remove to/from personal list
         */
        $('.save').click(function() {
            if (this.checked) {
                $(this).next().text('Remove from personal list');
                var eventHtml = $(this).closest('.day-event').html();
                var eventMonth = $(this).closest('.day-event').attr('date-month');
                var eventDay = $(this).closest('.day-event').attr('date-day');
                var eventNumber = $(this).closest('.day-event').attr('data-number');
                $('.person-list').append('<div class="day" date-month="' + eventMonth + '" date-day="' + eventDay + '" data-number="' + eventNumber + '" style="display:none;">' + eventHtml + '</div>');
                $('.day[date-month="' + eventMonth + '"][date-day="' + eventDay + '"]').slideDown('fast');
                $('.day').find('.close').remove();
                $('.day').find('.save').removeClass('save').addClass('remove');
                $('.day').find('.remove').next().addClass('hidden-print');
                remove();
                sortlist();
            } else {
                $(this).next().text('Save to personal list');
                var eventMonth = $(this).closest('.day-event').attr('date-month');
                var eventDay = $(this).closest('.day-event').attr('date-day');
                var eventNumber = $(this).closest('.day-event').attr('data-number');
                $('.day[date-month="' + eventMonth + '"][date-day="' + eventDay + '"][data-number="' + eventNumber + '"]').slideUp('slow');
                setTimeout(function() {
                    $('.day[date-month="' + eventMonth + '"][date-day="' + eventDay + '"][data-number="' + eventNumber + '"]').remove();
                }, 1500);
            }
        });

        function remove() {
            $('.remove').click(function() {
                if (this.checked) {
                    $(this).next().text('Remove from personal list');
                    var eventMonth = $(this).closest('.day').attr('date-month');
                    var eventDay = $(this).closest('.day').attr('date-day');
                    var eventNumber = $(this).closest('.day').attr('data-number');
                    $('.day[date-month="' + eventMonth + '"][date-day="' + eventDay + '"][data-number="' + eventNumber + '"]').slideUp('slow');
                    $('.day-event[date-month="' + eventMonth + '"][date-day="' + eventDay + '"][data-number="' + eventNumber + '"]').find('.save').attr('checked', false);
                    $('.day-event[date-month="' + eventMonth + '"][date-day="' + eventDay + '"][data-number="' + eventNumber + '"]').find('span').text('Save to personal list');
                    setTimeout(function() {
                        $('.day[date-month="' + eventMonth + '"][date-day="' + eventDay + '"][data-number="' + eventNumber + '"]').remove();
                    }, 1500);
                }
            });
        }

        /**
         * Sort personal list
         */
        function sortlist() {
            var personList = $('.person-list');

            personList.find('.day').sort(function(a, b) {
                return +a.getAttribute('date-day') - +b.getAttribute('date-day');
            }).appendTo(personList);
        }

        /**
         * Print button
         */
        $('.print-btn').click(function() {
            window.print();
        });
  }

};

I can display the default schedule without problems. But when I change the organ in select and modify the month using the click event:

$('.btn-next').on('click', function(e) {            
            var monthNumber = $('.month').attr('data-month');
            console.log(monthNumber);
            if (monthNumber > 11) {
                $('.month').attr('data-month', '0');
                var monthNumber = $('.month').attr('data-month');
                yearNumber = yearNumber + 1;
                setMonth(parseInt(monthNumber) + 1, mon, tue, wed, thur, fri, sat, sund);
            } else {
                setMonth(parseInt(monthNumber) + 1, mon, tue, wed, thur, fri, sat, sund);
            };
        });


        $('.btn-prev').on('click', function(e) {            
            var monthNumber = $('.month').attr('data-month');
            if (monthNumber < 2) {
                $('.month').attr('data-month', '13');
                var monthNumber = $('.month').attr('data-month');
                yearNumber = yearNumber - 1;
                setMonth(parseInt(monthNumber) - 1, mon, tue, wed, thur, fri, sat, sund);
            } else {
                setMonth(parseInt(monthNumber) - 1, mon, tue, wed, thur, fri, sat, sund);
            };
        });

The click event works but repeats. For example: I am in December/2016 and I click for January it displays February/2017. Debugging saw that it runs twice the click event.

The code to display the "agenda" via select looks like this:

$("#sel-sec-org").on('change', function () {
        $('.list').empty();
        var agendaOrgao = $("#sel-sec-org").val();
        calendar.init(agendaOrgao);
    });

When the application starts, it runs:

calendar.init(agendaOrgao);

When I modify select to select another organ it runs again:

calendar.init(agendaOrgao);

How to prevent on-click not to be executed twice?

2 answers

2


You must "schedule" the event in a block of code that will only run once. Apparently you are doing this within another event that is shot several times. In this case, the event is not overwritten but lined up.

A solution would be to add a .unbind( "click" ), thus removing the previously added event. Thus:

 ...
 $('.btn-next').unbind( "click" ).on('click', function(e) {            
            var monthNumber = $('.month').attr('data-month');
            console.log(monthNumber);
            if (monthNumber > 11) {
 ...

But just in case you really need to reset the event click.

  • Solved. Thank you very much!

1

Try this before adding click events:

$("#foo").unbind("click");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.