11

I have a re sizable div. While trying to resize it the whole page is getting selected with blue color even though I didn't intend to in iE and Edge. I have tried many solutions shown on web but nothing worked. Below is my code. I am unable to prevent default action by event on mouse move. I am listening on ownerDocument for mouse move event.

Below code is working as expected in chrome and mozilla

I have seen in console by inspecting in evt variable, before stop propagation prevent default is true, after stop propagation prevent default is false. Same as google chromes behavior but still dont get why is whole page getting selected

React Code:

 <div className="resizer"
      tabIndex={-1}
      onMouseDown={this.MouseDown}
 />


private MouseDown(evt: any) {
        this.viewState.resizing = true;
        const {ownerDocument} = ReactDOM.findDOMNode(this);
        ownerDocument.addEventListener('mousemove', this.MouseMove);
        ownerDocument.addEventListener('mouseup', this.MouseUp);

        this.setState(this.viewState);
    }

private MouseMove(evt) {
        this.viewState.width = width;
        this.viewState.height = height;


         if (evt.preventDefault) {
            evt.returnValue = false;
            evt.preventDefault();
        }
        else {
            evt.cancelBubble = true;
        }


        this.setState(this.viewState);
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Labeo
  • 5,831
  • 13
  • 47
  • 77

3 Answers3

5

Instead of making evt.preventDefault(); in mouse move make it in mousedown/Click event itself

private MouseDown(evt: any) {
        this.viewState.resizing = true;
        const {ownerDocument} = ReactDOM.findDOMNode(this);
        evt.preventDefault();
        evt.stopPropagation();
        ownerDocument.addEventListener('mousemove', this.MouseMove);
        ownerDocument.addEventListener('mouseup', this.MouseUp);

        this.setState(this.viewState);
    }
Labeo
  • 5,831
  • 13
  • 47
  • 77
2

If the issue is that the page gets selected with blue color, there is another approach to prevent selection.

Try this :

<body onselectstart="return false">
Jay
  • 1,478
  • 1
  • 10
  • 9
  • But we cant completely remove that functionality. Here we only want to prevent that functionality only when we are resizing the div element. – Labeo Aug 04 '17 at 19:31
  • Have you tried this approach using `addEventListener` and `removeEventListener`?. I'm guessing you have a `onDragStart` or `onMouseDown` events and other events when the interaction ends like `onDragEnd` or `onMouseUp`. Another alternative you could try is GreenSock's Draggable tool https://greensock.com/draggable – Rodrigo Aug 07 '17 at 05:10
1

Try this pattern:

if (event.preventDefault){ 
  event.preventDefault();
} 
else { 
  event.returnValue = false; 
}
Our_Benefactors
  • 3,220
  • 3
  • 21
  • 27