(function(window, $) { var $some = $(.some-class-matching-one-element-in-a-tree-of-one-hundred-thousand'); if ($some.length < 1) { return; } var $closest = $some.closest('.some-other-random-class'); if ($closet.length < 1) { return; } var $window = $(window); $window.on('scroll.foo', $.throttle(function() { if ($some.offset().top > $window.scrollTop()) { $window.off('scroll.foo'); $some.on('click.foo', function() { if ($closest.is('[chosen]')) { $closest.addClass('blue'); $some.removeAttr('chosen'); } }); } })); }(window, jQuery));