Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing functions as function parameters in JavaScript

im trying to change functions that are called in if else condition of handleIntersect function through parameters of called observeElement function like this:

window.addEventListener("load", (event) => {
  observeElement('.menu-nav-area', 1st funtion to call, 2nd function to call );
  observeElement('.menu-quick-area', 3rd funtion to call, 4th function to call );
}, false);

Can’t figure out how to pass these params as functions, so they are called instead isObserved and isNotObserved functions in handleIntersect.

Here is the code, that works, but calls only functions specified in handleIntersect:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

window.addEventListener("load", (event) => {
  observeElement('.menu-nav-area');
}, false);

function observeElement(element) {
  let target = document.querySelectorAll(element);
  let observer;
  createObserver();

  function createObserver() {
    let options = {
      root: null,
      rootMargin: '0px',
      threshold: 1.0
    }
    observer = new IntersectionObserver(handleIntersect, options);
    target.forEach(function (k){
    observer.observe(k);
    });
  }

  function handleIntersect(entries, observer) {
    entries.forEach(entry => {
            document.querySelectorAll(element).forEach(function (e) {
      if (entry.intersectionRatio === 1) {
        isObserved();
    } else {
        isNotObserved();
    }
            });
    });
  }

  
  
  

  
  function isObserved() {
            console.log('menu is up');
  }
  function isNotObserved() {
            console.log('menu is down');
  }
}

Can it be done?
Thanks!

>Solution :

Functions can be passed like any other function argument.

function observeElement(element, isObserved, isNotObserved) {
  //... other implementation here...
  if (someCondition) {
    isObserved()
  } else {
    isNotObserved()
  }
}

Now you can call that function like so:

observeElement(
  '.menu-nav-area',
  () => console.log('observed'),
  () => console.log('not observed')
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading