Skip to content

Commit 1fc37c6

Browse files
committed
Recalculate image bounds when entering image (#5)
1 parent 669ef9b commit 1fc37c6

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/Magnifier.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ export default class Magnifier extends PureComponent {
8282
};
8383

8484
// Function bindings
85+
this.onMouseEnter = this.onMouseEnter.bind(this);
8586
this.onMouseMove = throttle(this.onMouseMove.bind(this), 20, { trailing: false });
8687
this.onMouseOut = this.onMouseOut.bind(this);
8788
this.onTouchMove = throttle(this.onTouchMove.bind(this), 20, { trailing: false });
@@ -93,6 +94,7 @@ export default class Magnifier extends PureComponent {
9394
componentDidMount() {
9495
// Add mouse/touch event listeners to image element (assigned in render function)
9596
// `passive: false` prevents scrolling on touch move
97+
this.img.addEventListener('mouseenter', this.onMouseEnter, { passive: false });
9698
this.img.addEventListener('mousemove', this.onMouseMove, { passive: false });
9799
this.img.addEventListener('mouseout', this.onMouseOut, { passive: false });
98100
this.img.addEventListener('touchstart', this.onTouchStart, { passive: false });
@@ -107,6 +109,7 @@ export default class Magnifier extends PureComponent {
107109

108110
componentWillUnmount() {
109111
// Remove all event listeners
112+
this.img.removeEventListener('mouseenter', this.onMouseMove);
110113
this.img.removeEventListener('mousemove', this.onMouseMove);
111114
this.img.removeEventListener('mouseout', this.onMouseMove);
112115
this.img.removeEventListener('touchstart', this.onMouseMove);
@@ -116,6 +119,10 @@ export default class Magnifier extends PureComponent {
116119
window.removeEventListener('scroll', this.calcImgBoundsDebounced, true);
117120
}
118121

122+
onMouseEnter() {
123+
this.calcImgBounds();
124+
}
125+
119126
onMouseMove(e) {
120127
const { mgMouseOffsetX, mgMouseOffsetY } = this.props;
121128

@@ -135,6 +142,8 @@ export default class Magnifier extends PureComponent {
135142

136143
onTouchStart(e) { // eslint-disable-line class-methods-use-this
137144
e.preventDefault(); // Prevent mouse event from being fired
145+
146+
this.calcImgBounds();
138147
}
139148

140149
onTouchMove(e) {
@@ -175,7 +184,9 @@ export default class Magnifier extends PureComponent {
175184
}
176185

177186
calcImgBounds() {
178-
this.imgBounds = this.img.getBoundingClientRect();
187+
if (this.img) {
188+
this.imgBounds = this.img.getBoundingClientRect();
189+
}
179190
}
180191

181192
render() {

0 commit comments

Comments
 (0)