1

I couldn't find a solution to this, but the second this after mousedown will not work. I've seen different things about binding it but I haven't had any luck. (It works everywhere else in the code).

$(".rightArrow").click(function () {       
    var stop_slide = parseInt($(this).prev().css("marginLeft"));      
    scroll_size = $(this).prev().children().size() * 177 * -1;      
    if(stop_slide > scroll_size){
        var int00; // declared here to make it visible to clearInterval. 
        $(this).mousedown(function(){
            int00 = setInterval(function() { 
                $(this).prev().css( { marginLeft : "-=1px" } ); 
            }, 1);
        }).mouseup(function() {
            clearInterval(int00);
        });

    }

});
Lew
  • 1,248
  • 8
  • 13
Haru
  • 1,361
  • 2
  • 15
  • 40

1 Answers1

1

The this from the setInterval is different than the this from mousedown. Simply use a self variable, this way:

$(".rightArrow").click(function() {
  var stop_slide = parseInt($(this).prev().css("marginLeft"));
  scroll_size = $(this).prev().children().size() * 177 * -1;
  if (stop_slide > scroll_size) {
    var int00; // declared here to make it visible to clearInterval.
    $(this).mousedown(function() {
      var self = this;
      int00 = setInterval(function() {
        $(self).prev().css({
          marginLeft: "-=1px"
        });
      }, 1);
    }).mouseup(function() {
      clearInterval(int00);
    });
  }
});

Each function declared via the function statement has its own context (this), hence, you need to store the previous context into a variable to access it in another function.

Another way is to use bind:

 int00 = setInterval(function () {
    $(this).prev().css(...);
 }.bind(this));

This will bind the current context (the current this) to the setInterval callback.

And if you use , you can use arrow functions:

// the `this` from here
int00 = setInterval(() => {
   // will be the `this` from here
});

The arrow functions have no context––they inherit the current context.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474