Caroline Beltran
Caroline Beltran

Reputation: 918

Javascript context within a function

I am binding a function to an event.

$('div.my_div').bind("mouseenter", timerFunc);

The problem that I have is that my context changes and I cannot access my elements. I must admit that javascript context is terribly confusing to me:

function timerFunc() {
    //alert('Square ' + $(this).attr('data-somevalue') + ' named function called!');
    var count_to = 10;
    var count = 0;
    var countup = setInterval(function () {
        count++;
        $(this).find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square
        //self.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square
        if (count == count_to) {
            count = 0;
        }
    }, 750);
}

Please help

Upvotes: 0

Views: 60

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Store $(this) in a variable and use it in your nested function:

function timerFunc() {
    //alert('Square ' + $(this).attr('data-somevalue') + ' named function called!');
    var elem = $(this);//$(this) is stored in elem variable
    var count_to = 10;
    var count = 0;
    var countup = setInterval(function () {
        count++;
    //so you can use it here in nested function
        elem.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square
        //self.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square
        if (count == count_to) {
            count = 0;
        }
    }, 750);
}

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59232

setInterval executes in global context that is window, so this is window. So cache the variable and use it instead

var that = this;
var countup = setInterval(function () {
    count++;
    $(that).find('.countup').html(count + ' seconds!');
    if(count == count_to) {
       count = 0;
    }
}, 750);

Upvotes: 2

Related Questions