I’m using some jQuery and infinite scrolling and some of the new content that is getting pulled in via the infinite scroll uses some simple jQuery for some hover effects etc.
$(".grid-landing-page a").hover(function () {
$(this).children('.preview-project-title').toggleClass("preview-project-title-on");
});
I’ll need to add this to the callback of the infinite scroll, like I’ve already done with the masonry I’m using:
function( newElements ) {
var $newElems = $( newElements );
$('.grid-landing-page-container').masonry( 'appended', $newElems );
}
I’m curious to learn if it’s a good idea to make my toggleClass code into a global variable so I can then call it back in the infinite scroll newElements. If so, any help on how I could do this? Or if there’s a better way to do this, any help would be appreciated.
Thanks,
R
Avoid globals wherever possible. In your case, event delegation is a better option. If you’re new to this, the idea is this:
Instead of binding events literally to the elements you’re interested in, bind one event to a mutual container, and then check to see which element actually triggered it. This has obvious performance benefits where many elements are concerned.
You may prefer to change my choice of container (body) to something more specific.
What’s happening behind the scenes there is the event technically fires every time the mouse is hovered over the body – but until the event is deemed to have been kicked off by an element matching
.grid-langing-page a, jQuery doesn’t fire its callback code.Because this contextual check is done, therefore, at the point of event firing, rather than at the point of event binding (your original code), it works with both current and future matching elements. No need to re-bind.