Reputation: 1531
I am trying to get the relative coordinates of the mouse in an element in React using jQuery.
My code doesn't seem to be working and there are no console errors.
code:
index.html
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="stylesheets.css" >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="ja.js" type="text/javascript"></script>
<title>Where's Waldo</title>
</head>
<div id="root"></div>
</body>
</html>
ja.js (jQuery function)
jQuery(function($) {
var x,y;
$("#waldo1").mousemove(function(event) {
var offset = $(this).offset();
x = event.pageX- offset.left;
y = event.pageY- offset.top;
$("#coords").html("(X: "+x+", Y: "+y+")");
});
});
component
import React, { Component } from 'react'
import Timer from './timer'
class Level1 extends Component {
render () {
return (
<div>
<div id="gameBoard">
<img id="waldo1" src={require('../images/waldo1(1).jpg')} alt="waldo"/>
</div>
<h2 id="coords"></h2>
<Timer start={Date.now()}/>
</div>
) // return
} // render
} //component
export default Level1
I hear jQuery doen't play nice with react. Is my syntax correct or is there a better way entirely?
Thank you.
Upvotes: 32
Views: 109551
Reputation: 361
This is almost exactly the same answer with Carlos Martinez but with functional component and hooks:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [coord, setCoord] = useState({ x: 0, y: 0 });
const handleMouseMove = (e) => {
setCoord({ x: e.screenX, y: e.screenY });
};
return (
<div className="main" onMouseMove={handleMouseMove}>
<h1>
Mouse coordinates: {coord.x} {coord.y}
</h1>
</div>
);
}
Link to codesandbox: https://codesandbox.io/s/github/artidata/mouse-coordinate
Upvotes: 3
Reputation: 4878
You can try this:
import React, { Component } from "react";
class ClassCursorPosition extends Component {
constructor(props) {
super(props);
this.state = {
x: 0,
y: 0
};
}
logMousePosition = e => {
this.setState({
x: e.clientX,
y: e.clientY
});
};
componentDidMount() {
window.addEventListener("mousemove", this.logMousePosition);
}
render() {
return (
<div>
X- {this.state.x} Y - {this.state.y}
</div>
);
}
}
Actually there are three things you can consider, here I mention clientX, clientY you can search for pageX, pageY and secrrenX, screenY as well.
pageX, pageY => depends on mouse position according to page.( scrollable page)
screenX, screenY => depends on mouse position according to screen ( height and width of different screens)
Upvotes: 3
Reputation: 4510
As others have mentioned, the issue is that react has not rendered your component to the DOM when jQuery tries to attach the event listener.
You don't need jQuery to do this at all, a better approach is to use the React events:
class Application extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
}
_onMouseMove(e) {
this.setState({ x: e.screenX, y: e.screenY });
}
render() {
const { x, y } = this.state;
return <div onMouseMove={this._onMouseMove.bind(this)}>
<h1>Mouse coordinates: { x } { y }</h1>
</div>;
}
}
Example pen: https://codepen.io/CarlosEME/pen/XWWpVMp
Upvotes: 63
Reputation: 498
This should work for you:
jQuery(function ($) {
var x, y;
$(document).on('mousemove', '#waldo', function (event) {
x = event.pageX;
y = event.pageY;
$("#coords").html("(X: " + x + ", Y: " + y + ")");
});
});
Upvotes: -1
Reputation: 29
The issue (and the reason jQuery and react don't go well together) is likely that react has not rendered to the DOM that element by the time jQuery is trying to attach the event listener.
You should look at attaching event listeners using reacts methods. https://facebook.github.io/react/docs/events.html#mouse-events
Upvotes: 0