0

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

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.