Home > front end >  Fire an event via click of an element
Fire an event via click of an element

Time:05-03

I've attached onClick in a component (it's a icon) inside div.
What i want is when that component is clicked, "wheel" event listener should be fired

   const [isArrowClicked,setIsArrowClicked] = useState(false);
   return(
     ...stuff
     <div className="downArrow" >
       <CgArrowLongDown onClick={()=>setIsArrowClicked(true)} />
     </div>
   )

This way i'm getting to know whether that icon is clicked or not.

Now i want to somehow call 'wheel' event listener something like this:

  if(isArrowClicked){
    window.addEventListener("wheel", (event) => {
       // stuff
    }
  }

But it should work for both, meaning when scroll is actually done using mouse as well as, when that component is clicked, 'wheel' event should be fired.

please help.

CodePudding user response:

Im not sure if I understad what you are trying to achive. If you want to call the same function for both event you can use the same function for both event such as:

const myFunction = () => {
    // do stuff
}
window.addEventListener("wheel", myFunction)

and in the returned template:

<CgArrowLongDown onClick={myFunction} />

If you want to have the wheel listener to only do the stuff once the button is pushed you have to switch the if and the event listener in your code such as:

window.addEventListener("wheel", (event) => {
    if(isArrowClicked){
        // stuff
    }
}
  • Related