I need to make a hidden button visible when hovering over an adjacent text. This is being done through onMouseEnter
and onMouseLeave
events.
But when clicking on the text besides, I need to make the button completely visible and stop the onMouseLeave
event.
So far what I have tried: trying to remove the onMouseLeave
event using removeEventListener
.
I know we could do this with the help of a variable like:
const mouseOut = (divId) => {
if (!wasClicked)
document.getElementById(divId).style.visibility = "hidden";
}
But since I have way too may different buttons and text, I do not want to use variables either.
<div className="step-buttons" onMouseEnter={mouseOver.bind(this, 'feature')}
onMouseLeave={mouseOut.bind(this, 'feature')}
onClick={showButtonOnClick.bind(this, 'feature')}>Test Suite
</div>
Is there anything that could help me here?
Any suggestion would be welome, Thanks in advance :)
Way 1: You can mount an eventlistener for leaving in the MouseEnter function and remove it in the onClick eventhandling with refs like so:
constructor(props) {
super(props);
this.text;
this.onMouseLeave = this.onMouseLeave.bind(this);
}
onMouseEnter(){
//apply your styles
this.text.addEventListener('mouseleave', this.onMouseLeave);
}
onMouseLeave(){
//remove your styles
}
showButtonOnClick(){
//remove the eventlistener
this.text.removeEventListener('mouseleave', this.onMouseLeave);
}
render(){
return(
<div ref={(thiscomponent) => {this.text = thiscomponent}}
onMouseEnter={this.onMouseEnter.bind(this, 'feature')}
onClick={this.showButtonOnClick.bind(this, 'feature')}>
Test Suite
</div>);
}
The ref ist just a reference for your div, so that you can mount the eventlistener to it.
You have to bind the function in the constructor, as .bind(this)
will create a new function when you call it, to prevent mounting the eventhandler multiple times.
Way 2(probably better): Another method would be to save the click on the text in the state, and conditionaly change what your onMouseLeave function does based on that:
constructor(props) {
super(props);
this.state={
clicked: false,
}
}
onMouseEnter(){
//apply your styles
}
onMouseLeave(){
if(!this.state.clicked){
//remove styles
}
}
showButtonOnClick(){
this.setState({clicked: true});
}
render(){
return(
<div
onMouseEnter={this.onMouseEnter.bind(this)}
onMouseLeave={this.onMouseLeave.bind(this)}
onClick={this.showButtonOnClick.bind(this)}>
Test Suite
</div>);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With