0

Here is my snippet. Container is an ul element and div is its parent and scrollable. The code contains a resizeObserver function that monitor the size of ul container element. My problem is how can I make variable val global in (console.log('The global variable is: ' + val);) and access it from outside of the function? When I run snippet, the error says this val is not defined. I replaced it with an array and no chance.

  const container = $("#contacts")[0];
  const div = $(".scrollable.scrollable-y")[5];

  let resizeObserver = new ResizeObserver((entries) => {
     for (entry of entries) {
         div.scrollTop = div.scrollHeight;
         var val = div.scrollHeight;
     }
  });

  resizeObserver.observe(container);

  console.log('The global variable is: ' + val);

UPDATE: ok, I read the question and answers. Now, how can I pass a callback to resizeobzerver?

  • by actually making `val` a global variable, like your console log claims it is (you currently have it as being _declared_ inside the observer handling function, so that's what it's scoped to. And using the legacy `var`, too, which you shouldn't be using in modern code anymore). You're already using a global `container` and `div`, so just do what you did for those. However, on a programming note: don't call your vars `div` and `val`, give them real names so that three weeks from now you can at a glance see what this code does instead of wondering what's supposed to be in those variables =) – Mike 'Pomax' Kamermans Sep 16 '22 at 17:47

0 Answers0