Search code examples
jqueryliveeach

using .each on elements loaded after DOM


I am having some issues selecting a series of links injected by JS dynamically. Basically a youtube list is built and loaded into the DOM. Now I would like to add a little bit more flare to it (without CSS animations, my challenge here, testing limits on dynamic jQuery pages really and having fun)

But it just won't select the elements loaded after the DOM and I'm tried numerous searches for a solution to no avail. Though I have had a couple bears, and it's been my birthday for 1 minute so far. Yay, happy birthday!

Here is what I'm trying and you can see it in action (rather failing) here

        $('.featured-video-link').each(function(){  // featured-video-links is added after DOM too
            $(this).live({
                mouseenter: function () {
                    $(this).find('.feat-vid-title').animate({ 'backgroundColor': 'rgba(62, 132, 210, 0.8)', 'color': 'rgba(255,255,255,1.0)' }, 'slow');
                },
                mouseleave: function () {
                    $(this).find('.feat-vid-title').animate({ 'backgroundColor': 'rgba(0,0,0,0.5)', 'color': 'rgba(255,255,255,0.8)' }, 'slow');
                }
            });         
        });

Solution

  • You can use following syntax and you don't need to loop,

    $(document).on({
        mouseenter: function () {
            $(this).find('.feat-vid-title').animate({
                'backgroundColor': 'rgba(62, 132, 210, 0.8)',
                'color': 'rgba(255,255,255,1.0)'
            }, 'slow');
        },
        mouseleave: function () {
            $(this).find('.feat-vid-title').animate({
                'backgroundColor': 'rgba(0,0,0,0.5)',
                'color': 'rgba(255,255,255,0.8)'
            }, 'slow');
        }
    }, '.featured-video-link');