I want to display true in a paragraph when mousemove is active and false when it is not active. tried an if statement but didn't work
$(document).ready(function() {
var Clickcount = 1;
$(".chimp").mousemove(function(e) {
if (Clickcount % 2) {
$('.chimp').css({
'top': e.clientY - 20,
'left': e.clientX - 20
});
}
});
$("body").mousemove(function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
$(".cords").html("clientX " + x + " clientY= " + y);
});
$(document.body).on('click', function() {
Clickcount++;
});
});
I'm not quite sure what you mean with mousemove is active. If you want to check if the mouse is insida a specific element or not you can use something like this:
$(".chimp").hover(function () {
$("#bool").text('true');
},function () {
$("#bool").text('false');
});
Demo
But if you want to detect if the mouse has stopped moving, you can try it with this code-snippet:
var timeout;
$(".chimp").mousemove(function () {
$("#bool").text('true');
clearTimeout(timeout);
timeout = setTimeout(function() {
$("#bool").text('false');
}, 1000);
});
This will trigger if the mouse is not moved for 1 second. You can adjust the treshold for that easily, just edit the number in the timeout-function.
Demo
Use "html" instead of "body"
$("html").mousemove(function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
$(".cords").html("clientX " + x + " clientY= " + y);
});
.cords {
width: 20em;
height: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="cords"></div>
here you go
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Drag Me</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
#dragg
{
position: absolute;
background-color: red;
height: 200px;
width: 200px;
}
p{
position: relative;
top: 210px;
right: 5px;
}
</style>
</head>
<body>
<div id="dragg">
red
</div>
<p id="bool"></p>
<script>
$(document).ready(function () {
$('#dragg').on({
mousedown: function (e) {
$(window).data({
down:true,
oX: e.offsetX,
oY: e.offsetY,
el:this
})
},
mouseup: function (e) {
$(window).data('down',false)
},
})
$(window).on({
mousemove: function (e) {
var data=$(window).data()
if (data.down) {
$("#bool").text('true');
$(data.el).css({
left: e.clientX - data.oX,
top: e.clientY - data.oY
});
}
else{
$("#bool").text('false');
}
},
})
});
</script>
</body>
</html>
Related
I have an element which I would like to move with the mouse.
var troll = document.getElementById('troll');
troll.addEventListener('dragover', (e) => {
e.preventDefault();
e.target.style.left = e.clientX + 'px';
e.target.style.top = e.clientY + 'px';
}, false);
img {
width: 100px;
cursor: pointer;
position: absolute;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>
From left to right and from top to bottom it works OK. Not perfect, since the very first move takes a whole space and it doesn't look smooth. But the main problem is that I can't move from right to left or from bottom to top.
Any help would be appreciated.
You wanna use drag not dragover, and some logic to know where you're going up or down or left or top.
var troll = document.getElementById('troll');
var X,Y = 0;
troll.addEventListener('drag', (e) => {
e.preventDefault();
if (e.clientX > X)
{
e.target.style.left = X + 'px';
}
else if (e.clientX < X)
{
e.target.style.left = X-- + 'px';
}
if (e.clientY > Y)
{
e.target.style.top = Y + 'px';
}
else if (e.clientY < Y)
{
e.target.style.top = Y-- + 'px';
}
X = e.clientX;
Y = e.clientY;
}, false);
img {
width: 100px;
cursor: pointer;
position: absolute;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>
I'm new to coding and trying to make a game were I move my div along the x and y axis. When I run code I get an error in the marginLeft variable as well as the marginTop. I included these variables because I want successive keydown strokes to continue to move div. I would like to code using only jquery if possible.
var player = $('#player');
var marginleft = $('#player').offset().left;
var margintop = $('#player').offset().top;
function movePlayer(e) {
if (e.keydown==39) {
marginleft +=2;
player.css('left', marginleft + 'px');
}
if (e.keydown==37) {
marginleft -=2;
player.css('left', marginleft + 'px');
}
if (e.keydown==40) {
margintop +=2;
player.css('top', margintop + 'px');
}
if (e.keydown==38) {
margintop -=2;
player.css('top', margintop + 'px');
}
}
#player {
width: 50px;
height: 50px;
background-color: red;
left: 0px;
top: 0px;
position: absolute;
}
body {
height: 100%;
width: 100%;
background-color: green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="player"></div>
</body>
</html>
Your code worked fine when I modified it to use e.which in the event listeners. I also attached the event listener in the bottom of the snippit.
Click inside the game before using the arrow keys: https://jsfiddle.net/CoryDanielson/kchrv4t4/
var player = $('#player');
var marginleft = $('#player').offset().left;
var margintop = $('#player').offset().top;
function movePlayer(e) {
if (e.which==39) {
marginleft +=2;
player.css('left', marginleft + 'px');
}
if (e.which==37) {
marginleft -=2;
player.css('left', marginleft + 'px');
}
if (e.which==40) {
margintop +=2;
player.css('top', margintop + 'px');
}
if (e.which==38) {
margintop -=2;
player.css('top', margintop + 'px');
}
}
$(document.body).on('keydown', movePlayer);
You should use e.which when using jQuery. There's a lot of discrepancies between browsers and key codes. which is the safe way to determine keycodes. https://api.jquery.com/event.which/
When I run code I get an error in the marginLeft variable as well as the marginTop
This phare let me think you are defining and initializing the variables outside the document ready...
If you need to move your div only inside visible document area a solutioon can be:
//
// declare global variables and functions outside the
// document ready
//
var player;
var marginleft;
var margintop;
var docWidth;
var docHeight;
function movePlayer(e) {
if (e.which==39) {
if (marginleft >= docWidth) {
return;
}
marginleft +=2;
player.css('left', marginleft + 'px');
}
if (e.v==37) {
if (marginleft<=0) {
return;
}
marginleft -=2;
player.css('left', marginleft + 'px');
}
if (e.which==40) {
if (margintop >= docHeight) {
return;
}
margintop +=2;
player.css('top', margintop + 'px');
}
if (e.which==38) {
if (margintop<=0) {
return;
}
margintop -=2;
player.css('top', margintop + 'px');
}
}
//
// On document ready: set the variables and
// add the event listener for keydown event
//
$(function () {
player = $('#player');
marginleft = $('#player').offset().left;
margintop = $('#player').offset().top;
docWidth = $(document).width() - player.width();
docHeight = $(document).height() - player.height();
$(document).on('keydown', function(e) {
movePlayer(e);
});
});
#player {
width: 50px;
height: 50px;
background-color: red;
left: 0px;
top: 0px;
position: absolute;
}
body {
height: 100%;
width: 100%;
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="player"></div>
I have the following jQuery and JS code:
$(function() {
function addMouseEvents() {
$('img').addClass('close-overlay-active')
var close_H = ($('.close-overlay-active').height() * 1.2);
var close_W = ($('.close-overlay-active').width() * 1.2);
document.addEventListener('mousemove', function(e) {
// console.log('move');
// console.log(e.pageX + " " + e.pageY );
var mouseX = e.pageX,
mouseY = e.pageY;
$('.close-overlay-active')
.css({
top: (mouseY - close_H),
left: mouseX - close_W
});
});
}
addMouseEvents();
});
The desired behaviour ofcourse is for the 'x' mark to be slightly above the cursor. That does happen most of the time , but sometimes the 'x' appears below the cursor that is towards the right bottom of the cursor and sometimes 1000px below the cursor. Why is this happening ? e.pageY seems to be returning the wrong value sometimes Why ?
Can anybody please explain this behavior please ?
FIDDLE HERE
Try this:
$(function() {
function addMouseEvents() {
$('img').addClass('close-overlay-active')
var close_H = ($('.close-overlay-active').height());
var close_W = ($('.close-overlay-active').width());
document.addEventListener('mousemove', function(e) {
// console.log('move');
// console.log(e.pageX + " " + e.pageY );
var mouseX = e.pageX,
mouseY = e.pageY;
$('.close-overlay-active')
.css({
top: (mouseY - close_H),
left: mouseX - close_W / 2
});
});
}
addMouseEvents();
});
img {
position: absolute;
top: 0;
left: 0;
}
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #b0e2ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="fixed">
<img src="https://cdn3.iconfinder.com/data/icons/sympletts-free-sampler/128/circle-close-128.png">
</div>
To get cursor exactly in the center, refer this FIDDLE
Why when the ball is placed relative positioning when you press the mouse it bounces? Absolute positioning is when this doesn't happen.
var ball = document.querySelector('.ball');
ball.onmousedown = function(event) {
var shiftX = event.pageX - getCoords(this).left,
shiftY = event.pageY - getCoords(this).top;
this.style.position = 'relative';
this.zIndex = 10000;
function move(event) {
this.style.left = event.pageX - shiftX + 'px';
this.style.top = event.pageY - shiftY + 'px';
}
move.call(this, event);
document.onmousemove = function(event) {
move.call(ball, event);
};
this.onmouseup = function(event) {
document.onmousemove = this.onmouseup = null;
};
return false;
};
ball.ondragstart = function() {
return false;
};
function getCoords(elem) {
var box = elem.getBoundingClientRect();
return {
top: box.top + window.pageYOffset,
left: box.left + window.pageXOffset
};
}
body {
margin: 50px;
}
img {
cursor: pointer;
}
<img class="ball" src="https://js.cx/clipart/ball.svg" alt="" />
I guess it's because of the padding of the body element. Please explain.
it seems i found answer
Implementing drag and drop on relatively positioned elements in JavaScript
and as it says, with relative position, your element contain offset of all objects in his parent-tag
and parent's margin and padding too
so when you try to get elemtn's position, you should count it's real offset in parent, see in my code example work with count index
<html>
<body>
<div id=obj1 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<div id=obj2 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<div id=obj3 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<script>
var dragObj, count=0;
function set_drag_drop(obj)
{
if(count>0){
// count margins and divs offset
// body{ margin:10px; }
// height:100px;
obj.adx = 10;
obj.ady = 10 + (count*100)
}else{
obj.adx = 0;
obj.ady = 0;
}
count++;
obj.onmousedown = function(e)
{
var rect = obj.getBoundingClientRect();
obj.dx = rect.left - e.clientX;
obj.dy = rect.top - e.clientY;
obj.isDown = true;
dragObj = this;
}
obj.onmouseup = function(e)
{
obj.isDown = false;
}
document.onmousemove = function(e)
{
if(dragObj && dragObj.isDown)
{
dragObj.style.left = e.pageX -dragObj.adx+ dragObj.dx +"px";
dragObj.style.top = e.pageY -dragObj.ady+ dragObj.dy + "px";
}
}
}
set_drag_drop(document.getElementById("obj1"));
set_drag_drop(document.getElementById("obj2"));
set_drag_drop(document.getElementById("obj3"));
</script>
</html>
I found this example on my search.
But it is useless, because when the webpage has long height, and my <div> block isn't on the top, when I scroll the page, there are different distances with different PageY or clientY, so the movable <div> can not exactly go after the mouse cursor.
Here's what I've tried so far:
jQuery("#requestStatusChart").mouseover(function (event) {
var maskVal = '<span id="floatTip" style="position:absolute"><span id="hintdivlogistics" class="RMAHintdivlogistics">' +
+'</span><div class="clear"></div></span>';
jQuery(this).find(".DashboardMask").append(maskVal)
ShowHintInfoLogistics("abc");
//when onmouse out ,remove the elements I appended before.
jQuery(this).find(".DashboardMask").mouseout(function () {
if (typeof jQuery("#hintdivlogistics") != undefined) {
jQuery("#floatTip").fadeOut("slow").remove();
}
});
//move current row
jQuery(this).find(".DashboardMask").mousemove(function (event) {
_xx = event.clientX;
_yy = event.clientY;
_yyPage = event.pageY;
var pos = jQuery(this).position();
console.log((pos.left + " " + pos.top));
jQuery("#floatTip").css({ "top": _yy + "px", "left": _xx - 180 + "px",
"border": "2px solid red"
}).fadeIn("slow");
console.log("x:" + _xx + ",y:" + _yy / _yyPage * _yy);
return false;
});
return false;
});
I don't know of any way to do that reliably, given that you don't know the position of the mouse without a mouse event. You could keep track of the mouse position on mousemove, but as this snippet demonstrates it's far from ideal.
function mousemoved(event) {
var f = document.querySelector('#floater');
console.log(event);
f.style.top = event.pageY + f.scrollTop + 'px';
f.style.left = event.pageX + 'px';
}
document.querySelector('#container').addEventListener('mousemove', mousemoved);
#container {
overflow: scroll;
position: relative;
}
#content {
height: 4000px;
background: lightblue;
}
#floater {
position: absolute;
border: 1px solid black;
padding: 1em 2em;
}
<div id="container">
<div id="floater">Hi</div>
<div id="content">content just to make the container taller</div>
</div>
I have solved this problem use another way.
in X axis we can do like this.
content means your main program width,codes adapted all resolution.
var widthContent = jQuery("#content").width();
jQuery("#floatTip").css("left", _xx - (window.screen.width - widthContent)/2 + "px");