Home > database >  How to prevent the onmouseleave event from being triggered outside the browser?
How to prevent the onmouseleave event from being triggered outside the browser?

Time:05-11

I have a little try below. When i enter the mouse inside of the basket, a dropdown with a button appears. When we click the button a modal appears.I want the modal to close only when the close modal button is clicked. But when we take the mouse out of the browser the hideDropdown function is triggered and the modal closes. I sent the hideDropdown function as a prop to the component whose Modal state was updated, but this time only the hideDropdown function worked and the isModalShow state was not updated. How can i solve this?

Demo: https://codesandbox.io/s/jolly-buck-1lgmiu

CodePudding user response:

Can you try to unlink the Modal from the isDropdownShow property so that it can be toggled only the button OpenModal and CloseModal... Just a workaround

import "./styles.css";
import Dropdown from "./Dropdown";
import { useState } from "react";

export default function App() {
  const [isDropdownShow, setIsDropdownShow] = useState(false);
  const [isModalShow, setIsModalShow] = useState(false);
  
  const showDropdown = () => {
    setIsDropdownShow(true);
  };

const showModal = () => {
    setIsModalShow(true);
  };
const hideModal = () => {
    setIsModalShow(false);
  };

  const hideDropdown = () => {
    setIsDropdownShow(false);
  };

  return (
    <div
      className="App"
      
    >
      <span 
      onm ouseEnter={showDropdown}
      onm ouseLeave={hideDropdown}
      className="basket">Basket</span>
      {isDropdownShow && <button onClick={()=>showModal}> Open Modal<button/>}
      <Dropdown hideModal={hideModal} IsModalShow={IsModalShow} />
    </div>
  );
}

CodePudding user response:

Use onmouseup event instead of on mouseleave.

To ensure for a specific mouse up from the busket element, compare event.target to the basket element like so:

let myEl = document.getElementById("...")
myEl.onmouseup = (e) => e.target==myEl? hideDropDown(myEl):;

This is vanilla JS. Hopefully you'll sucseed translating it to your react project without too much work. Let me if it is solved!

  • Related