1
votes

Basically I'm implementing the infinite-scroll (.com) on my WordPress blog and here's the code:

HTML

<div id="photos" class="display-fix">
    <?php while ( have_posts() ) : the_post(); ?>
    <img src="<?php $url = get_post_thumbnail_id(); $url = wp_get_attachment_image_src($url,'medium'); $url = $url[0]; echo $url; ?>">      
    <?php endwhile; ?>
</div>
<div id="pagination" class="clear right">        
    <?php if(function_exists('wpex_pagination')) { wpex_pagination(); } ?>
</div>

JS

$('#photos').infinitescroll({
    navSelector  : ".next:last", // selector for the paged navigation (it will be hidden) 
    nextSelector : "a.next:last", // selector for the NEXT link (to page 2) 
    itemSelector : "#photos img", // selector for all items you'll retrieve 
    loading: {
        finished: undefined,
        finishedMsg: '',
        img: "<?php echo get_template_directory_uri(); ?>/images/preloader.gif",
        msg: null,
        msgText: '',
        selector: null,
        speed: 'slow',
        start: undefined
    }
});

$('#photos img').hover(function(){
    alert('Works');
});

CSS

#photos {
    width: 100%;
    padding: 20px;
}
#photos img {
    width: 504px;
    margin: 3px;
    float: left;
}
#infscr-loading {
    position: absolute;
    width: 100px;
    height: 100px;
    left: 50%;
    margin-left: -50px;
    bottom: 10px;
}
#infscr-loading img {
    width: 100px;
    height: 100px;
}

What happens is that when the images pop up when I scroll down, the hover alert doesn't work, it only works on the first images displayed! The ones that popped up don't work.

Any reason why? I'm using $(document).ready(function() { should I use anything else?

2

2 Answers

0
votes

You need to use delegation.

Change:

$('#photos img').hover(function(){
    alert('Works');
});

to

$('#photos img').on('mouseover', function(){
    alert('Works');
});
0
votes

It is because hover event is attached to elements that are initially visible, just handle the finished event of infinitescroll:

$('#photos').infinitescroll({
    navSelector  : ".next:last", // selector for the paged navigation (it will be hidden) 
    nextSelector : "a.next:last", // selector for the NEXT link (to page 2) 
    itemSelector : "#photos img", // selector for all items you'll retrieve 
    loading: {
        finished: registerHover,
        finishedMsg: '',
        img: "<?php echo get_template_directory_uri(); ?>/images/preloader.gif",
        msg: null,
        msgText: '',
        selector: null,
        speed: 'slow',
        start: undefined
    }
});

registerHover();

function registerHover()
{
    $('#photos img').hover(function(){
       alert('Works');
    });
}