Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modify it to only close when scrolled outside but not inside?

function HomeFilterModal({ visible, onClose }) {
  const toggle = useSelector(selectModal);
  const dispatch = useDispatch();

  const handleOnClose = (e) => {
    if (e.target.id === "container") onClose();
  };

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY >= 10) {
        onClose();
      }
    };

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);
  if (!visible) return null;

  return (
    <div
      id="container"
      onClick={handleOnClose}
      className="fixed top-24 bottom-0 left-0 right-0 bg-black bg-opacity-30 backdrop-blur-sm h-screen z-50 hidden sm:flex justify-center "
    >
      <div
        id="nonscroll"
        className="h-[28rem] w-2/3 bg-[#fafaf9] drop-shadow-md rounded-3xl flex flex-col items-center overflow-hidden overflow-y-scroll scrollbar-none snap-y
        "
      >
        <div className="flex items-center justify-between w-full px-4 py-4 border-b">
          <div
            onClick={() => dispatch(setModal(!toggle))}
            className="rounded-full border h-8 w-8 border-gray-600 hover grid place-items-center hover:border-0 hover:drop-shadow-2xl hover:shadow-black"
          >
            <XMarkIcon className="h-4 w-4" />
          </div>
          <p className="text-2xl tracking-wider">Filter</p>

          <p
            onClick={() => dispatch(resetFunc())}
            className="text-sm hover:underline pr-2 cursor-pointer"
          >
            Clear All
          </p>
        </div>

        <HomePriceFilter />
        <HomeLocationFilter />
        <HomeTypeFilter />
        {/* <div className="py-6 h-48 bg-white w-full text-transparent">hey</div> */}
      </div>
    </div>
  );
}

export default HomeFilterModal;

Answer №1

If you want to improve performance, consider utilizing the Intersection Observer API. This API is highly effective and efficient: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

While I haven't delved deeply into your code, creating an observer (as outlined in the documentation) can be done as follows:

let observer = new IntersectionObserver(callback, options);

By observing your parent view (the background element) like so:

let target = document.querySelector('#yourParentSelector');
observer.observe(target);

You can then trigger the close() function only when the observed background moves.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Even in report-only mode, Content Security Policy effectively blocks the execution of inline scripts

Currently, I have implemented a Content Security Policy (CSP) in 'Content-Security-Policy-Report-Only' mode with a specified report-uri. There is an inline JavaScript code running on the page that the CSP restricts. My initial expectation was tha ...

Issue with Reactjs API Call not functioning properly within Yii2

I am just starting to learn React js and I am using Yii2 as my backend. When I make an API request to Yii2, it returns a 500 error. I am not sure where I have gone wrong in my code. Below is my ReactJs code for the API call: fetch('localhost/learnin ...

ReactJS: Trouble encountered while parsing information from JSON data

Currently, I am facing an issue while trying to pass data from my JSON file to my ReactJS application. The error message that I am encountering is as follows: TypeError: Cannot read property 'mainPage' of undefined Upon console.logging siteDa ...

When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project: wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' ))); As part of testing, I used an $http. ...

A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript? Consider the two Records below: var dictionary1 : Record<string, string []> ={ 'fruits' : ['apple','banana', 'cherry'], 'vegeta ...

What methods can I use to minimize the frequency of the blue box appearing around text?

I successfully developed code that enables user interaction with text, triggering the opening of a modal box when clicked. In this modal box, the text turns red upon clicking, indicating activation of a checkbox. However, I notice that every time I intera ...

Retrieve information from a MySQL database and integrate it into a different application

This php script is used to generate a table with a "book" button next to each row. The goal is to extract the values of "phase" and "site" from the specific row where the "book" button is clicked, and transfer them to another form (in "restricted.php") fo ...

Struggling to implement a vertical scroll bar in HTML code?

<body ng-app="myApp" ng-controller="myCtrl"> <div ng-show = "dataFromRest" ng-repeat = "x in dataFromRest.posts" > <div class="tittle" style="width: 25%;"> <a href="" ng-click="showDi ...

navigate to a different section on the page with a series of visuals preceding it

When I try to navigate to a specific dom element on another page, the page initially works fine but then jumps to somewhere before that element. I believe this issue occurs because the page calculates the position before images load, and once the images ar ...

How can I verify if a date is after the current date using Node.js?

I am struggling to set up date validation that ensures the date is after the current date. This is what I have attempted so far: Router.post('/home', [ check('due_date') .isDate() .isAfter(new Date.now()) .wi ...

Is it feasible to display components in reverse order using JSX?

I have a component in my Nextjs/React.js app where I display a list of cards like this : <div className="grid grid-cols-1 lg:grid-cols-12 gap-12"> <div className="lg:col-span-8 col-span-1"> {posts.map((post, ...

Why is my custom function failing to operate on an array?

My function is created to organize and remove duplicates from a provided array. Below is an excerpt of the code: Bubble Sort - function organize(postsCollection, type, direction){ let target = postsCollection[0][type]; let swapp = false, ...

Encountered an error while running `npm init @eslint/config` and `npx create-react-app .`

When attempting to initialize an eslint config file for my node project using npm init @eslint/config, I encountered the following error. I've tried downgrading my node version, upgrading npm to the latest version, and clearing node cache, but nothing ...

The second node child process encounters execution issues in Linux

For a challenge, I needed to find a way to automatically restart my bot within itself. After some trial and error, I came up with a solution. However, when testing on a Raspberry Pi via ssh, the process exits after the first child process ends. Surprisingl ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

Discover the position of the element that was clicked within the group of elements sharing the

Here is my HTML code: <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value= ...

Watch for event triggered after completion of input field with ng-modal

One of my challenges involves implementing a text input field that prompts users to enter their name: <input type="text" ng-modal="form.name" placeholder="Enter NAME"> I've also set up a watch function to monitor changes in the form's nam ...

Dynamic links with Node Acl

Utilizing the npm module Acl to establish an ACL system has been my current focus. You can check out the homepage of this module at: https://github.com/OptimalBits/node_acl. While the documentation provides straightforward examples for granting role acces ...

Ways to restrict the quantity of Firebase compound indexes required for querying with various filters

I'm in the process of developing a Firestore project that includes group chats and forums where users can filter posts based on various criteria: Number of likes Presence of attachments (photos and/or files) 4 Tags (Questions, Exams, Assignments, Not ...