0

How do you do this?

So far this is what I'm trying:

var blogHeaders = $('.coa-content h2');
$(window).scroll(function() {
    blogHeaders.each(function(i) {
        console.log(blogHeaders[i].offset().top);
    });
})

This block of code is giving me the following:

VM941:6 Uncaught TypeError: blogHeaders[i].offset is not a function

I tried looking up "offset() for each item in loop" on here, these were the first 4 results:

VBA For Each Loop only excutes once and then stops

WordPress Custom Post Loop / alternating layout for each item

Shifting scatter points for each array for delta x

Check if array has [0][1][2] or just single item

Unfortunately, none of these answers are relevant to my question.

I googled "offset() multiple elements in loop javascript" but couldn't find any relevant answers there, either.

Is there a way to do this? Or am I taking the wrong approach here?

kawnah
  • 3,204
  • 8
  • 53
  • 103
  • does `console.log($(blogHeaders[i]).offset().top);` work ? – Hozeis Aug 26 '21 at 17:11
  • take a look at https://stackoverflow.com/a/625941/4825796 – Hozeis Aug 26 '21 at 17:12
  • interesting, it does, howcome I have to do that? I thought the variable represented that, no? – kawnah Aug 26 '21 at 17:23
  • this `$()` pretty much wraps a DOM object into a jquery object. `.offset()` can only be called on a jquery object. Also like the link shows, when you take a `jquery` object and do `blogHeaders[0]` it returns a regular DOM object. – Hozeis Aug 26 '21 at 17:28
  • @kawnah The iteration variable in `.each()` contains the DOM element, not the element wrapped in a jQuery object. – Barmar Aug 26 '21 at 17:39
  • This is true of most of the jQuery functions that take callback functions. – Barmar Aug 26 '21 at 17:39
  • It's the reason you have to write `$(this)` in jQuery event handlers. – Barmar Aug 26 '21 at 17:40

0 Answers0