Javascript division positioning - javascript

Here's my simple code.It contains division, which moves on dragging with mouse (on x axis) anywhere on screen.Everything works perfect on first drag, but on second division comes back to it's original position, which is centre of screen.I know why does this happen, but can't figure out how to fix it.My point is to continue moving division from coords where previous drags moved it.
<!DOCTYPE html>
<html>
<head>
</head>
<body style="overflow:hidden">
<style>
#screen
{
width:200px;
height:300px;
position:absolute;
top:0;bottom:0;left:0;right:0;
margin:auto;
border-style:solid;
}
</style>
<script>
var exit=0;
document.onmousedown=function(e)
{
exit=1;
x=e.pageX;
document.onmousemove= function(e)
{
if(exit==1)
{
y=e.pageX;
final=x-y;
document.getElementById("screen").innerHTML=final;
document.getElementById("screen").style.left=final+"px";
}
};
};
document.onmouseup=function(e)
{
exit=0;
}
</script>
<div id="screen">
</body>
</html>

You want to store the "final" value so that you can use it as an offset on the next click. What's happening is that you are using the mouse down and mousemove X difference to move the object, but on second click you are not taking into consideration that the object was offseted by the previous "final" value and it has to be moved with that offset in mind!
Here's the code snippet working, and the jsfiddle link below:
var exit=0;
var final = 0;
document.onmousedown=function(e)
{
exit=1;
x=e.pageX + final;
document.onmousemove= function(e)
{
if(exit==1)
{
y=e.pageX;
final=x-y;
document.getElementById("screen").innerHTML=final;
document.getElementById("screen").style.left=final+"px";
}
};
};
document.onmouseup=function(e)
{
exit=0;
}
jsfiddle:
http://jsfiddle.net/dcasadevall/NELWW/

Related

Updating the mouse position while scrolling

I am trying to find the latest updated current mouse position relative to the whole document. I have set up a scroll event.
Since this event doesn't contain mouse location I have nested another event listener of mousemove inside this scroll event.
Even though, it works the problem I am facing is that if the user keeps the pointer in the same position and simply scrolls with the wheel, the latest position is not being updated unless I move the mouse.
What should I do? What can I use to detect the mouse position? I want simplest answer because I am learning css and js.
Here is my code:
document.addEventListener('scroll', (e) => {
document.addEventListener('mousemove', (e1) => {
total_scroll = window.scrollY + e1.clientY;
console.log("Current Pos: " + total_scroll);
})
})
body {
height: 2000px;
}
I think the best solution would be to separate these listeners, and keep updating some variable with current mouse position, and then, on scroll - just use the variable.
My previous answer was not proper, so I'll give another one:
<html lang="en">
<head>
<title>Document</title>
<style>
body {
height: 2000px;
}
</style>
</head>
<body>
<script>
let clientScrollY = 0;
document.addEventListener('mousemove', (e1) => {
clientScrollY = e1.clientY;
})
document.addEventListener('scroll', (e) => {
total_scroll = window.scrollY + clientScrollY;
console.log("Current Pos: " + total_scroll);
})
</script>
</body>
</html>
Also here is solution if you want to update onscroll and onmousemove.
<html lang="en">
<head>
<title>Document</title>
<style>
body {
height: 2000px;
}
</style>
</head>
<body>
<script>
let clientScrollY = 0;
let totalScrollY = 0;
function updateTotalScrollY(){
totalScrollY = window.scrollY + clientScrollY;
console.log(totalScrollY);
}
document.addEventListener('mousemove', (e1) => {
clientScrollY = e1.clientY;
updateTotalScrollY();
})
document.addEventListener('scroll', (e) => {
updateTotalScrollY();
})
</script>
</body>
</html>

is there something like a 'move()' command in jQuery?

I'm quite new to programming as a whole and extremely new to jquery. I'm trying to make it so every time I press the W key, my cube moves upward. I can make it grow in width with the 'width("+=__")' command, but I don't want it to do that. Is there something like that width command but instead of width it changes positioning? if not, is there a simple way I can make this work?
Here's what i've got right now. Instead of changing width, I want to change the positioning somehow.
document.addEventListener('keypress', function(event){
if (event.key === 'w') {
document.getElementById('player').style.left = $('#player').width("+=50");
}
});
Try using absolute positioning on the element, then changing the top property:
document.addEventListener('keypress', function(event) {
console.log()
if (event.key === 'w') {
$('#player').css("top", parseInt($('#player').css("top")) - 50 + "px");
}
});
#player {
position:absolute;
top:150px;
height:50px;
width:50px;
background-color:blue;
transition: top 0.25s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Click on this snippet, then presss "W" key to move up</p>
<div id="player"></div>

Moving a sprite image using arrow keys in JavaScript

I have to animate a robo such that it would move around an HTML5 Canvas.
Here's my image: https://i.stack.imgur.com/oecS2.png
The instructions I have to work on my animation are:
If you are not pressing a button, the skeleton should not move and should just be facing you.
If you press the right arrow key or “d” then it should move to the right.
If you press the left arrow key or “a” then it should move to the left.
If you press the up arrow key or “w” then it should move up.
If you press the down arrow key or “s” then it should move down
If it gets to the edge of the canvas, it should keep walking but not move
I haven't been able to find any helpful resources that would guide me to move my sprite image using arrow keys. And I know a bit of making an image move using mouse but not using arrow keys. But here's what I've tried so far.
JavaScript:
var tID;
function stopAnimate()
{
clearInterval(tID);
}
function animateScript()
{
var position = 256;
const diff = 256;
tID = setInterval ( () => {
document.getElementById("image").style.backgroundPosition = `-${position}px 0px`;
if (position < 1536)
{
position = position + diff;
}
else
{
position = 256;
}
}, 100);
}
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' type='text/css' href='Robot.css'>
</head>
<body>
<h2>Animation</h2>
<div id ="demo">
<p id="image" onmouseover="animateScript()" onmouseout="stopAnimate()"></p>
</div>
<script src="Animate.js"></script>
</body>
</html>
CSS:
body
{
background: white;
color: black;
}
#image
{
height: 256px;
width: 256px;
background: url('robo.png') 0px 0px;
}
The code above isn't the right thing that I need but I was just testing it using my knowledge about moving sprites using a mouse but I need some help on rotating my image using arrow keys. Any help would be appreciated!

How do you listen for a HTML element moving in JavaScript?

I have an HTML element that I need to track another element. Specifically, I need to have the top left and top right corners of both elements be positioned the same. When a window gets resized, the resize event gets triggered and I can adjust the position of the dependent element. However, if the element being tracked is repositioned (but not resized), I do not see any DOM event.
How can we find out if a DOM element has been moved? We are using the latest jQuery.
Here is a code sample.
Note that elementOne and mouseTracking divs are there to show elements that get moved for "some" reason that is outside the control of my code.
This code works for the elementOne case.
MouseTrackingTracker does not track a moving element.
ResizerTracker does not put the border around the complete text in the overflow case.
I would like the trackingDivs to move and resize no matter the reason for the tracked element's reasons for changing.
This code relies on the window resize being the hooked event. Hooking some event that fires when the element changes its dimensions is closer to what I need.
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js"></script>
<style type="text/css">
#elementOne { float : right;width : 200px; display:inline-block}
#resizer { float : left; display:inline-block}
.trackedDiv { width:50px; height:50px; background-color: blue }
.trackingDiv { position:absolute; z-index: 1; border:3px green; border-style: solid;}
</style>
<script>
$(function() {
$( window ).bind("resize",function(){
$("#elementOne").trigger("reposition");
$("#mouseTracking").trigger("reposition");
$("#resizer").trigger("reposition");
});
var repositionFunction = function(selfish, element){
var self = $(selfish);
var offset = self.offset();
var selfTop = offset.top;
var selfLeft = offset.left;
var selfWidth = self.width();
var selfHeight = self.height();
$(element).css({
top: selfTop,
left: selfLeft,
width : selfWidth,
height : selfHeight
});
}
$(document).mousemove(function(ev){
$("#mouseTracking").position({
my: "left bottom",
of: ev,
offset: "3 -3",
collision: "fit"
});
});
var timedShort = function() {
$('#resizer').html("Really short").resize();
setTimeout(timedLong, 10000);
}
var timedLong = function() {
$('#resizer').html("Really longggggggggggggggggggggggggggggggggggggggggggggggggggg text").resize();
setTimeout(timedShort, 10000);
}
setTimeout(timedLong, 10000);
$("#elementOne").bind("reposition",
function() { repositionFunction(this, "#elementOneTracker"); });
$("#mouseTracking").bind("reposition",
function() { repositionFunction(this, "#mouseTrackingTracker"); });
$("#resizer").bind("reposition",
function() { repositionFunction(this, "#resizerTracker"); });
});
</script>
</head>
<body>
<div class="trackedDiv" id="mouseTracking">tracks mouse</div>
<div class="trackingDiv" id="mouseTrackingTracker"></div>
<div style="clear:both;"></div>
<div class="trackedDiv" id="resizer">resizer: resizes</div>
<div class="trackingDiv" id="resizerTracker"></div>
<div class="trackedDiv" id="elementOne">elementOne: floats to the right</div>
<div class="trackingDiv" id="elementOneTracker"></div>
</body>
</html>
You can fire custom events with jquery whenever you reposition the element.
$( window ).bind("resize",function(){
$("#elementOne").css({
top: 200,
left: 200
}).trigger("reposition");
});
// and now you can listen to a "reposition event"
$("#elementOne").bind("reposition",function(){
var self = $(this);
$("#elementTwo").css({
top: self.css("top"),
left: self.css("left")
});
});
So you can provide event hooks yourself with some manual coding, which is useful since cool events like DOMAttrModified and so on, are not fully supported in all browsers. The downside, you have to do it all yourself.
Unfortunately, there are no reliable events to tell you when an element moves or is resized. You could resort to polling the element, though that won't necessarily be the most performant solution:
setInterval(repositionElement, 10);
Another option is to make your element "track" the other element purely through CSS. For this to work, you'll need a "wrapper" around the element you're tracking, and the other element:
#wrapper-around-element-to-track
{
position: relative;
}
#tracked-element
{
position: absolute;
/* set top and left to position, if necessary */
}
#tracking-element
{
position: absolute;
/* set top and left to position, if necessary */
}
Since you're already using jQuery, you can also use the resize event plugin to simulate the resize event on any element, but if I recall the last time I looked at it, it simply does the polling like I mentioned.
There is the DOMAttrModified event, but its only impleneted in Firefox and Chrome. But as you need a JavaScript function to start the element moving, you can firing a custom event with Jquery in this place.

Need help with animation on JavaScript without jQuery

I have got a div object for example (Simple Image), and I need my picture to move to right and left and backward without any frame and border. My picture will collide with end (right side of my page) and move backward to left and then action with right side too. This will be only on JavaScript.
Edit:
<html>
<head>
<script>
function dvig () {
var xx = 50;
var corner_left=200 +'px';
var corner_right=100 +'px';
var move; var move2;
var dv=document.getElementById("adam");
if(dv.style.left<=corner_right) {
move=1;
move2=1;
}
if(dv.style.left>=corner_left) {
move2=0;
move=0;
}
if(move=1) {
dv.style.left=parseInt(document.getElementById("adam").style.left)+xx;
}
if (move2=0) {
move=0;
dv.style.left=parseInt(document.getElementById("adam").style.left)-xx;
}
}
function chustro() {
setInterval("dvig()", 100);
}
</script>
</head>
<body onload="chustro()">
<img id="adam" style="position: absolute; top: 100px; left: 100px; width: 40px; height: 40px; background-color: red">
</body>
</html>
Your going to have to setup a iterative process that runs every X milliseconds. Each time its run you have to update the div's position a bit and check if it hits a side and reverse direction.
function doWork{
// move current direction a little
// check if past the left edge and change directions
// check if past the right edge and change direction
}
setInterval(doWork, 10);
Update:
Based on your code, check this example:
http://jsfiddle.net/HT9A4/

Categories