I have a site which loads items and uses the jquery infinite scroll plug in to load more items as a user scrolls.
When a user hovers over an item, more small divs are shown over the item. Simple. Which divs are shown on hover depends on which page a user is on, therefore they are dependant on knowing which page they are on. I use a simple variable to sort that out.
I use the following js to decide which divs are shown. eg from homepage
<script>
$(".list_item_image").mouseenter(function () {
$(this).children(".gl_view2").show();
$(this).children(".gl_relist").show();
});
$('.list_item_image').mouseleave(function() {
$(this).children(".gl_view2").hide();
$(this).children(".gl_relist").hide();
});
</script>
The divs (gl_view2 & gl_relist) are initially loaded but with display:none;
Now, this js is loaded into the footer to ensure its after the divs in question.
Lets say I have infinite scroll set to update 15 items at a time
This all works perfectly (meaning on mouseenter the divs which should be shown/overlaid, are shown) for the first 15 items, but after that the items load but the mouseenter simply does not work anymore. I'm guessing this is because the js has loaded and when the next items are loaded onto the page the js doesn't have any effect.
To load the next items with infinite-scroll I am using:
<nav id="page_nav"><a href="/pages/infinScrollGather.html?page_offset=2¤tpage=homepage"></a></nav>
I've also tried loading the js in after each item but still only works for the first 15.
I have also tried but this didn't work at all:
$("body").on("mouseenter", ".list_item_image", function () {
...
});
$("body").on("mouseleave", ".list_item_image", function () {
...
});
Has anyone come across anything like this before? Any ideas for a fix?
you should use event delegation with on()
method like so
$("body").on("mouseenter", ".list_item_image", function () {
...
});
$("body").on("mouseleave", ".list_item_image", function () {
...
});
this will attach your handlers also on newer elements injected later on the DOM via ajax
only if you are using an older version of jQuery use delegate()
, on()
otherwise
Fixed (I hope so anyway)
It seems the js was missing being wrapped in: $(document).ready(function(){ ... });
Thanks for all help.
来源:https://stackoverflow.com/questions/12139508/infinite-scroll-javascript-already-fired