I have this that I've been messing with:
$('.container').mousedown(function(e) {
$('.coords').text(e.pageX + ' : ' + e.pageY);
});
.container {
width: 300px;
height: 300px;
background-color: white;
border: 2px solid black;
margin: 0 auto;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
</div>
<div>Coords: <p class='coords'> </p> </div>
I'm trying to program it such that when you click inside the box and move the mouse around the coordinates will also change - then if you leave the box, it's not updated. Right now, the coordinates will only change when you let go of the mouse button and then click again. Help?
You need to create more that a mousedown function. You need to use mousemove as well. Here are the docs on that, https://api.jquery.com/mousemove/
You could do something like this (fiddle).
var mouse_clicked;
$('.container').mousedown(function(e) {
mouse_clicked = true;
});
$('.container').mouseup(function(e) {
mouse_clicked = false;
});
$('.container').mouseleave(function(e) {
mouse_clicked = false;
});
$('.container').mousemove(function(e) {
if (mouse_clicked) {
$('.coords').text(e.pageX + ' : ' + e.pageY);
}
});
Here is a different way of doing it that looks a little cleaner
var mouse_clicked;
$('.container').on({
'mousedown': function() {
mouse_clicked = true;
},
'mouseup': function() {
mouse_clicked = false;
},
'mouseleave': function() {
mouse_clicked = false;
},
'mousemove': function(e) {
if (mouse_clicked) {
$('.coords').text(e.pageX + ' : ' + e.pageY);
}
}
});