Kenny Kenny - 1 month ago 19
AngularJS Question

JQuery toggleClass() on and then back off (or remove)

I am using an angular directive to have a left and right column of a page.

<left-column></left-column>
and
<right-column></right-column>
. When the user clicks an
<a href="#target1">Target 1</a>
then it finds the corresponding
<div id="target1">Target 1</div>
in the right column.

That works fine and what I'm trying to do now is after it's clicked the specific div's background should kind of flash or something, I have some css for it. So I want to toggle that css class, then a second later remove that class (or toggle it off).

I'm trying to use a
setTimeout()
function but it doesn't seem to be working. Any ideas?

My error is:

Uncaught TypeError: Cannot read property 'toggleClass' of undefined


My js is:

var highlight = {

onReady: function() {

$(document).on('click', 'left-column > div', function(event) {

var id = $('a', this).attr('href').split('#');
var target = $('right-column > div').find('#' + id[1]);

target.toggleClass('gas');
var junk = setTimeout(function(target) {
target.toggleClass('gas');
}, 1000);

event.preventDefault();

});

}

};


$(document).ready(highlight.onReady);

Answer

Your problem is that you're expecting target as an argument in the callback passed to setTimeout, but aren't actually passing any arguments so the target local to the setTimeout callback hides (shadows) access to the target available in the outer scope.

Removing target from the callback parameters will fix your error:

var junk = setTimeout(function(/* remove target from here */) {
  target.toggleClass('gas');
}, 1000);

Or you can explicitly pass it if you'd like but it would be redundant since its already available:

var junk = setTimeout(function(target) {
  target.toggleClass('gas');
}, 1000, target); // <--- you can pass the target along here