‘this’ does not work properly in another event. I’m clueless as to why [duplicate]

You aren’t attaching the event handler correctly. This line:

$('.figure').click(toggleCarousel(this));

…is calling toggleCarousel with this immediately (that’s what the parens will do). What you really want is to pass the function object to .click():

$('.figure').click(toggleCarousel);

Update:

As @FelixKling pointed out, you’ll also want to pass the target of the event to the downstream functions; it looks like they expect an element, not the event. Also, bool will be reset to false each call, which is not what you want; you should put it in the closure:

var flag = false; // "bool" is a reserved word, changed the name
function toggleCarousel(event) {
    var element = event.target;
    if (flag) {
        stopCarousel(element);
    }
    else {
        startCarousel(element);
    }
    flag = !flag;
}

Leave a Comment