javascriptjquerymodular-design

Click event results an error `TypeError: this.$varName.on is not a function` which isn't a function


I have this exact code:

<span class="btn" id="setScheduleBtn">Set Schedule</span>
    <div id="reportSchedule" name="reportSchedule" style="display: none;">text</div>


<script type="text/javascript">
/******************/
/** Set Schedule **/ 
/******************/
(function() {

    var schedule = {

        report: [], 
        template: $('#report_schedule').html(),

        // Init functions
        init: function() {
            this.cacheDom();
            this.bindEvents();
        }, 
        // Cache elements from DOM
        cacheDom: function() {
            this.$setScheduleBtn = $('#setScheduleBtn'); 
            this.$reportSchedule = $('#reportSchedule');
        }, 
        // Set events
        bindEvents: function() {
            this.$setScheduleBtn.on('click', this.showReportScheduler.bind(this));
        }, 
        // Display on click
        showReportScheduler: function() {
            this.$reportSchedule.toggle();
        }

    };
    schedule.init();

})();
</script>

Running this code on my local machine project - I get this error result in the console: TypeError: this.$setScheduleBtn.on is not a function without toggling. jQuery is loaded in the tag. the html code comes before the script. jQuery JavaScript Library v1.3.2

This is a JSfiddle with the exact code which runs properly: https://jsfiddle.net/t6hprf4x/

What might be the problem?


Solution

  • According to the documentation The on function was added in version 1.7 that means that the version you're using doesn't have this function.

    You will have to use a newer version of the library or add the click listener using the click function.

    this.$setScheduleBtn.click(this.showReportScheduler.bind(this));