0

I have a div with animated scrolling, and it contains hundreds of dynamically generated divs using append().

Each div has its own unique id and I need to get a list of all div ids within view a few milliseconds after the animated scroll has stopped.

Once I have the ids I'll be able to call a php script to dynamically append the appropriate content to each one.

I have seen this post and while it is helpful, you need to know the id names first, and also have an event listener on each which means many hundreds of event listeners.

I could get the position of the inner wrapper div at the top and bottom of the visible area. That would give me a range to search in, but how can I search for any divs in that area?

Or is there another way?

Community
  • 1
  • 1
PaulMrG
  • 1,822
  • 2
  • 16
  • 20
  • check out the fiddle http://jsfiddle.net/Hwhrw/1/ – PaulMrG Apr 06 '12 at 13:36
  • I could record every div name as it's created into an array, then loop through and test each one to see if it's position is between the top and bottom visible wrapper values. I'm hoping there's a better way that would use less load on the browser/processor. – PaulMrG Apr 06 '12 at 13:58

1 Answers1

0

A possibility:
http://jsfiddle.net/Hwhrw/2/

$("#wrapper").children("div:visible").css("background-color", "#00CC00");

var $sc = $('#scrollable');
$sc.scrollTop(Math.random() * $('#wrapper').height());
var ids = [];
$('.abc').each(function() {
    var c = $(this).position().top + $(this).height() / 2;
    if (c > 0 && c < $sc.height()) {
        $(this).css('background-color', 'blue');
        ids.push($(this).attr('id'));
    }
});
alert(ids);​

I used the center point of the .abc divs for the calculation for simplicity.

Andy
  • 29,707
  • 9
  • 41
  • 58
  • This is the type of thing I was thinking of doing, however your code is better than what I would have ended up with. each() is looping through all divs which I expected to be too taxing on the client side. I implemented your code in my real script to give it a go and went up to approximately 3000 divs in the wrapper and it was fine in Chrome and FF, but as usual IE took it's sweet time to respond. Just one more thing, can I add more classes on this line somehow $('.abc').each(function() { ?, or will I have to duplicate the each() function for each class? (there are 8 classes) – PaulMrG Apr 06 '12 at 15:48
  • Got it sorted, for anyone else reading this, the syntax is $('div.abc, div.abd, div.abe').each(... for multiple classes. Thanks for your help Andy, much appreciated! – PaulMrG Apr 06 '12 at 16:11