0

i have problem that I can't understand:

var Copyright =
{

    onLoad: function () {
        this.initCopyrightMoving();
    },


    initCopyrightMoving: function () {
        $(".sidebar_toggle").click(function () {
            var copyright = document.getElementById("copyright-text");

            if (copyright.className == "copyright-menu-open") {
                this.decrease(280, 80, 10, copyright);
            }

            else
                copyright.className = "copyright-menu-open"

        });
    },

    decrease: function (actual_val, stop_val, step, copyright) {
        setTimeout(function () {
            if (actual_val == stop_val) {
                copyright.className = "copyright-menu-closed";
            }
            actual_val = actual_val - step;
            copyright.style.paddingLeft = parseInt(actual_val) + "px";
            this.decrease(actual_val, stop_val, step, copyright);
        }, 10);
    }

};

and when I call initCopyrightMoving in line this.decrease(280, 80, 10, copyright);, I get this error:

copyright.js:14 Uncaught TypeError: this.decrease is not a function
    at HTMLAnchorElement.<anonymous> (copyright.js:14)
    at HTMLAnchorElement.dispatch (jquery-1.11.2.min.js:3)
    at HTMLAnchorElement.r.handle (jquery-1.11.2.min.js:3)

can sm tell me what I did wrong? And also because I can't run next part of script can you tell me if decrease function is written good, I mean will it run properly.

2 Answers2

0

this here is element $(".sidebar_toggle") you clicked.

Try defining var self = this; before jQuery handler and call self.decrease inside handler

this.decrease inside setTimeout will also not work for similar reason. Fix is the same

Anarion
  • 1,048
  • 6
  • 16
0

This is because this (context) changes when it's inside the click callback. One way you can stop the error is by preserving a copy of this and using that inside the callback.

initCopyrightMoving: function() {

  var _this = this; // some developers use `self`

  $(".sidebar_toggle").click(function() {
    var copyright = document.getElementById("copyright-text");
    if (copyright.className == "copyright-menu-open") {
      _this.decrease(280, 80, 10, copyright);
    } else {
      copyright.className = "copyright-menu-open"
    }
  });
},

Here's a useful article on scope and context in JavaScript.

Andy
  • 61,948
  • 13
  • 68
  • 95