简体   繁体   中英

JQUERY infinit scrolling, applying a script to newly loaded elements

I am using Yii framework. I want to have infinit scrolling for my contents (pictures). This part works fine. My only problem is that I have to have a script to have some effects on my images (like making them bigger and showing some text when they get clicked). This script works fine when I do not have infinite scroll:

<?php

   Yii::app()->clientScript->registerScript('overlayimage','
        $(".overlay").hide();

        $(".box").click(function() {

            if($(this).hasClass("col5"))
            {
                $(this).removeClass("col5").addClass("col3").fadeIn(400).find(".overlay").fadeOut(400);
                $(".items").masonry("reload");
                $(this).clearQueue();
            }

            else
            {
                $(".items").find(".col5").removeClass("col5").addClass("col3").fadeIn(400).find(".overlay").fadeOut(400);
                $(this).removeClass("col3").addClass("col5").fadeIn(400).find(".overlay").fadeIn(400);
                $(".items").masonry("reload");
                $(this).clearQueue();
            }

        })
   ',CClientScript::POS_READY);
?>

However when there is infinit scroll (The script is in CClientScript::POS_LOAD ), the script doesnot work on the newly added elements. I tried to add the same script after infinit scroll in CClientScript::POS_LOAD but in this case for some of the elements the script gets executed 2 times and I think it is not the right way to repeat the code in different places.

Anybody can help me to find out where I should put my script to be executed also for the newly loaded elements?

Just in case here is the example page that has the problem.

Sounds like you're running into the issue where you're adding new items, I'm guessing .box elements for your images, and jQuery won't attach handlers to these. Another symptom of this would be that the jQuery interactions work on the elements that are there when your page is first loaded, but not on any new elements that you have scrolled to.

Instead of .click(), you'll need to use .on() . Specifically of interest to you should be the delegated events sections.

In any case, you'll probably need a format like:

$("<parentSelector>").on("click", ".box", function(event) { //do some fancy stuff here })

parentSelector needs to be an element that contains .box , and is a permanent portion of the page, ie is loaded on page load and does not go away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM