rsilva
rsilva

Reputation: 270

javascript object literal pattern constructor error

I am trying to organize my code using the object literal pattern, but I am getting an error: Uncaught ReferenceError: backToTop is not defined

Any ideas why?

Here's the code:

(function($){

  var Mk = {

    config: {},

    init: function(config) {
      backToTop();
      wow();
      progressBarAnimation();
      slabText();
    },

    backToTop: function() {
      $('body').append('<div id="toTop" class="btn btn-success"><span class="glyphicon glyphicon-chevron-up"></span> Back to Top</div>');
      $(window).scroll(function () {
        if ($(this).scrollTop() != 0) {
          $('#toTop').fadeIn();
        } else {
          $('#toTop').fadeOut();
        }
      }); 
      $('#toTop').click(function(){
        $("html, body").animate({ scrollTop: 0 }, 600);
        return false;
      });
    },

    wow: function() {
      var wow = new WOW({
        boxClass:     'wow',      
        animateClass: 'animated', 
        offset:       0,          
        mobile:       true,       
        live:         true        
      });
      wow.init(); 
    },

    progressBarAnimation: function() {
      $.each($('div.progress-bar'),function(){
        $(this).css('width', $(this).attr('aria-valuetransitiongoal')+'%');
      });
    },

    slabText:function() {
      $("h1.mklife").slabText({
        "viewportBreakpoint":400
      });
    },

    last:''

  };

  $(document).ready(Mk.init());
  window.Mk = Mk;

})(jQuery)

Upvotes: 1

Views: 156

Answers (2)

gafi
gafi

Reputation: 12784

backToTop is not a global variable so you need to call it using the object notation (this.backToTop)

The above solution would work but I recommend a cleaner approach using the revealing module design pattern, check this link (and the resources at the bottom of the page) on how to implement it https://carldanley.com/js-revealing-module-pattern/

Upvotes: 1

Musa
Musa

Reputation: 97717

The functions backToTop,wow,progressBarAnimation,slabText are methods of the Mk object, to access them reference the Mk object

init: function(config) {
  Mk.backToTop();
  Mk.wow();
  Mk.progressBarAnimation();
  Mk.slabText();
},

or since init is also a method of the same object you can access the function with the this keyword

init: function(config) {
  this.backToTop();
  this.wow();
  this.progressBarAnimation();
  this.slabText();
},

Upvotes: 3

Related Questions