2

Is there any way to determine if an element is being observed already?

if ( element /* is not being observed */ ) observer.observe(element)
oldboy
  • 5,729
  • 6
  • 38
  • 86
  • 1
    No. The [API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) doesn't have that ability. – Ouroborus Jul 16 '23 at 07:51
  • @Ouroborus damn. alright. thanks for informing me – oldboy Jul 16 '23 at 09:02
  • @oldboy it's possible – Alexander Nenashev Jul 16 '23 at 11:01
  • @AlexanderNenashev how? – oldboy Jul 16 '23 at 11:21
  • 1
    Why do you need this? You can call multiple times observer.observe(elem) and it will still be observed only once by this observer. – Kaiido Jul 16 '23 at 14:10
  • @Kaiido i need to monitor a single element in a group of elements that are to be monitored one by one in order to make constant calculations based on the "focused" element without always looping through the group of elements. FWIW, the group of elements might sometimes be in the hundreds and, in addition to this, the group might be duplicated multiple times to facilitate infinite scrolling -- wait a second -- i guess i could just apply it to each and every element and use `entry.target` to identify the "focused" element. hopefully, this works – oldboy Jul 16 '23 at 21:16

1 Answers1

0

Monkey patch observe() and disconnect() methods. When calling observe() collect DOM elements associated with particular observer in a WeakSet for the observer stored in WeakMap. When calling disconnect() remove the observer from the map.

To get all elements observed collect all elements from the sets in the map.

Make sure your code executes at the very beginning.

Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17
  • im self-taught and that is one area where im lacking (i.e. manipulating properties of prototypes). can you provide a code example? and would i add it when the `DOMContentLoaded` event is fired? – oldboy Jul 16 '23 at 20:08