I am making a simple game using JS. In that I have to move the character left when we click on the A button in the keyboard. I got the Keycode and I am able to change the left property also, but only once. I saw many similar questions, but none of those answers helped.
Here's my code:-
HTML FILE:
<!-- The div that I wanna move -->
<div class="char-div">
<img src="game imgs/char-1.png" alt="" id="char-img">
</div>
CSS FILE:
.char-div{
/* styling of that div */
position: absolute;
/* top: 0; */
left: 350px;
bottom: 0;
}
JS FILE:
let char_div = document.getElementsByClassName('char-div')[0];
var char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
document.onkeydown = function(e){
if(e.keyCode == 65){
char_div.style.left = char_div_left - 20 + "px";
console.log(char_div_left)
}
if(e.keyCode == 68){
char_div.style.left = char_div_left + 120 +"px";
console.log(char_div_left)
}
}
You need to calculate left style of char_div in each key down event
let char_div = document.getElementsByClassName('char-div')[0];
document.onkeydown = function (e) {
var char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
if (e.keyCode == 65) {
char_div.style.left = char_div_left - 20 + "px";
// console.log(char_div_left)
}
if (e.keyCode == 68) {
char_div.style.left = char_div_left + 120 + "px";
// console.log(char_div_left)
}
}
.char-div {
/* styling of that div */
position: absolute;
/* top: 0; */
left: 350px;
bottom: 0;
}
<div class="char-div">
<img src="game imgs/char-1.png" alt="this is img" id="char-img">
</div>
You need to get these <div class="char-div"> <img src="game imgs/char-1.png" alt="" id="char-img"> </div> inside the onkeydown function
let char_div = document.getElementsByClassName('char-div')[0];
var char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
document.onkeydown = function(e) {
let char_div = document.getElementsByClassName('char-div')[0];
var char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
if (e.keyCode === 65) {
char_div.style.left = char_div_left - 5 + "px";
}
if (e.keyCode == 68) {
char_div.style.left = char_div_left + 5 + "px";
}
}
.char-div {
/* styling of that div */
position: absolute;
/* top: 0; */
left: 350px;
bottom: 0;
border: 1px solid green;
}
Your variable char_div_left doesn't update it's value on click, so it holds the initial value for all of the clicks.
I advise, however, against reading the value from computed styles altogether, just create a state variable:
let char_div = document.getElementsByClassName('char-div')[0];
let how_much_left = 350;
document.onkeydown = function(e){
if(e.keyCode == 65){
how_much_left -= 20;
char_div.style.left = how_much_left + "px";
console.log(how_much_left)
}
if(e.keyCode == 68){
how_much_left += 120;
char_div.style.left = how_much_left + "px";
console.log(how_much_left)
}
}
Here is more precise solution, this will only listen to the specific events.
let char_div = document.getElementsByClassName('char-div')[0];
let char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
document.onkeydown = function (e) {
if (e.keyCode == 65 || e.keyCode == 68) {
char_div_left = ( char_div_left + ( e.keyCode == 65 ? -20 : 120 ) );
char_div.style.left = char_div_left + "px";
}
}
When the right arrow key is pressed I would like to increment the left position of a div by 10px using the style property. Here is my script and what I've tried so far:
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if (k.keyCode == RightBtn) {
document.getElementById("test").style.left = document.getElementById("test").style.left + 10px;
}
}
#test {
position: relative;
left: 0px;
width: 25px;
height: 80px;
background-color: black;
}
<div id="test"></div>
The style property of a DOM element is essentially a dictionary with string key-value pairs. It expects a CSS key, and a proper string value.
Your current code comes out as left: 10px10px and that doesn't make much sense for CSS.
In order for this to work, you'd have to regard the px.
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if (k.keyCode == RightBtn) {
var moveEl = document.getElementById("test"),
currLeft = parseInt(moveEl.style.left || 0);
moveEl.style.left = (currLeft + 10) + 'px';
}
}
#test {
position: relative;
left: 0px;
width: 25px;
height: 80px;
background-color: black;
}
<div id="test"></div>
Further reading and examples - HTMLElement.style
Remove px from 10.
if (k.keyCode == RightBtn) {
document.getElementById("test").style.left = document.getElementById("test").style.left + 10;
}
Try following way:
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if(k.keyCode == RightBtn) {
document.getElementById("test").style.left = parseInt(document.getElementById("test").style.left || 0) + 10 + 'px';
}
}
I have a setInterval function that wont execute if the increment is less than 101ms. The timing will go any number above 100ms. I want to be able to increment the function by 10ms. offY and strtPos also become undefined when the timing goes below 101ms. How do I make it work the same as it is, but instead, have it incremented by 10ms?
var strtPos;
var offY;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 101); //<-- When I change that value to below 101, it prevents the code from working
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>
The short answer is you need to give offY a value that is not undefined initially, so I've rearranged the variables at the top of your code.
Originally, offY only gets a value after ~100ms (setInterval(st, 100)), and without a value that is not undefined the otherfunction's calculations won't work. So you needed the st function to execute first, hence requiring a value > 100.
var strtPos;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var offY = obj.offsetTop;
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 10);
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>
I have a bug in this code somewhere that cause the ship to fly faster and faster in space after returning from the planet. I cant figure this one out.
I set the speed to 0.1 so that its super slow in space. When you click on the planet, i run a function that will move canvas's off screen and use zindex to brong a div tag to the top of the stack. When you land and return to orbit, the ship will move slightly faster. After doing it about 10-15 times the ship moves far greater than the 0.1 speed that is set. I will include the html, js and css so you can run it to test.
Here is the whole code.
// Canvas Context's
var canvasMS = document.getElementById('MainScreen_cvs');
var ctxMain = canvasMS.getContext('2d');
var canvasShip = document.getElementById('Ship_cvs');
var ctxShip = canvasShip.getContext('2d');
var PlanetDiv = document.getElementById('PlanetDiv');
var OrbitReturn = document.getElementById('OrbitReturn');
var canvasPlanets = document.getElementById('Planets_cvs');
var ctxPlanets = canvasPlanets.getContext('2d');
var canvasHUD = document.getElementById('HUD_cvs');
var ctxHUD = canvasHUD.getContext('2d');
var canvasSurface = document.getElementById('Surface_cvs');
var ctxSurface = canvasSurface.getContext('2d');
// ----------------------------------End Canvas Context
var Player1;
var Planet1;
var planetClicked;
var gameWidth = canvasMS.width;
var gameHeight = canvasMS.height;
var mouseX = 10000;
var mouseY = 10000;
var SpaceMapX = 10;
var SpaceMapY = 10;
var SurfaceMap = 0;
var SurfaceMap2 = -1600;
var inSpace = true;
var onSurface = false;
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
// Load Images
var imgMap = new Image();
imgMap.src = 'images/bg1.png';
var imgButtons = new Image();
imgButtons.src = 'images/button_sprite.png';
var imgBlueWindow = new Image();
imgBlueWindow.src = 'images/blue_window.png';
var imgSprite = new Image();
imgSprite.src = 'images/sprite.png';
var imgPlanets = new Image();
imgPlanets.src = 'images/earthlike_p1.png';
var imgBluesky1 = new Image();
imgBluesky1.src = 'images/bluesky1.png';
var imgBluesky2 = new Image();
imgBluesky2.src = 'images/bluesky2.png';
imgMap.addEventListener('load',init,false);
// ------------- End Loading Images
//-------------------- Create Game Objects ----------------
function CreateGameObjects(){
Player1 = new Ship();
Planet1 = new Planet();
};
//---------------END CREATING GAME OBJECTS------------------
function init(){ //----------------------------------------------- GAME INITIALIZATION
document.addEventListener('keydown',checkKeyDown,false);
document.addEventListener('keyup',checkKeyUp,false);
document.addEventListener("mousedown", checkMouseDown, false);
document.addEventListener("mouseup", checkMouseUp, false);
CreateGameObjects();
Loop();
};
function Loop() { // ---------------- Main Game Loop
clearCtx();
DrawGameObjects();
requestAnimFrame(Loop);
};
function planetSurface(){
if(onSurface){
clearCtx();
HUD();
Player1.draw();
if(mouseY < 21 && mouseX > 693){
ReturntoOrbit();
}
planetClicked.drawSurfaceImg();
var CloseButton = '<button style="float:right;" type="button">Return to Orbit</button>' ;
OrbitReturn.innerHTML = CloseButton;
requestAnimFrame(planetSurface);
}
};
function DrawGameObjects(){
Player1.draw();
Planet1.draw();
HUD();
};
function HUD(){
canvasHUD.style.zIndex = "100";
if (onSurface){
ctxHUD.fillStyle = "#000";
ctxHUD.fillText("locSurface: " + planetClicked.locSurface, 20,30);
}
if (inSpace)
ctxHUD.fillStyle = "#fff";
ctxHUD.fillText("Speed: " + Player1.speed, 60,60);
ctxHUD.fillText("drawX: " + Player1.drawX, 600,40);
ctxHUD.fillText("drawY: " + Player1.drawY, 600,30);
// ctxHUD.fillText("Planet Clicked: " + Planet1.isClicked, 600,50);
}
//----------------------------------------------------------- Objects
/************************************************************************************/
//--------------------------------- SPACE SHIP --------------------------------------
function Ship(){
this.srcX = 0;
this.srcY = 0;
this.srcW = 60;
this.srcH = 60;
this.drawX = 20 ;
this.drawY = 50 ;
this.speed = 0;
this.surfaceSpeed = 10;
this.drift = 0.45;
this.w = 16;
this.h = 16;
this.isUpKey = false;
this.isDownKey = false;
this.isLeftKey = false;
this.isRightKey = false;
this.isSpacebar = false;
this.direction = "n/a";
this.isMoving = false;
this.isClicked = false;
this.surfX = 350;
this.surfY = 200;
};
Ship.prototype.draw = function() {
if(inSpace)
ctxShip.drawImage(imgSprite,this.srcX,this.srcY,this.srcW,this.srcH,this.drawX,this.drawY,this.w,this.h);
if(onSurface)
ctxShip.drawImage(imgSprite,this.srcX,this.srcY,this.srcW,this.srcH,this.surfX,this.surfY,this.w,this.h);
this.checkPos(planetClicked);
};
Ship.prototype.checkPos = function (PlanetX){
if(inSpace){
this.srcY = 0;
this.srcW = 60;
this.w = 16;
this.h = 16;
this.speed = 0.1;
//----------------------------- Move Ship and Map based on the speed of the ship.
if(this.isLeftKey){
this.drawX -= this.speed;
if(SpaceMapX >= 1){
SpaceMapX -= this.speed;
}
}
if(this.isRightKey){
this.drawX += this.speed;
if(SpaceMapX <= 2190)SpaceMapX += this.speed;
}
if(this.isDownKey){
this.drawY += this.speed;
if(SpaceMapY <= 2490)SpaceMapY += this.speed;
}
if (this.isUpKey) {
this.drawY -= this.speed;
if(SpaceMapY >= 1){
SpaceMapY -= this.speed;
}
}
if (SpaceMapY < 0) {SpaceMapY = 0;}
if (SpaceMapX < 0 ) {SpaceMapX = 0}
//--------------------------------------------------------------------END
//-----------------------------------Change Ship Graphic based on direction and map boundaries.
if(this.isUpKey) this.srcX = 360;
if(this.isDownKey) this.srcX = 120;
if(this.isLeftKey) this.srcX = 240;
if(this.isRightKey) this.srcX = 0;
if(this.isUpKey && this.isLeftKey) this.srcX = 300;
if(this.isUpKey && this.isRightKey) this.srcX = 420;
if(this.isDownKey && this.isLeftKey) this.srcX = 180;
if(this.isDownKey && this.isRightKey) this.srcX = 60;
if (this.drawX <= 5) this.drawX = 5;
if (this.drawY <= 5) {this.drawY = 5};
if (this.drawY >= 480) {this.drawY = 480};
if (this.drawX >= 780) {this.drawX = 780};
//----------------------------------------------------------------END
ctxMain.drawImage(imgMap,SpaceMapX,SpaceMapY,gameWidth,gameHeight,0,0,gameWidth,gameHeight);
}
if (onSurface) {
this.srcY = 240;
this.srcW = 92;
this.w = 93;
this.h = 60;
if(this.isLeftKey){
PlanetX.locSurface -= this.surfaceSpeed;
SurfaceMap += this.surfaceSpeed;
SurfaceMap2 += this.surfaceSpeed;
PlanetX.MapDirection = -1;
this.srcX = 93;
}
if(this.isRightKey){
PlanetX.locSurface += this.surfaceSpeed;
SurfaceMap -= this.surfaceSpeed;
SurfaceMap2 -= this.surfaceSpeed;
PlanetX.MapDirection = 1;
this.srcX = 0;
}
}
};
//------------------------------END OF SPACE SHIP ------------------------------------
//----------------------------- PLANET OBJECT INFO ------------------------------------
function Planet(){
this.srcX = 0;
this.srcY = 0;
this.srcW = 100;
this.srcH = 100;
this.w = 50;
this.h = 50;
this.coordX = 100;
this.coordY = 100;
this.planetType = "Small Earthlike Planet."
this.drawX = this.coordX - SpaceMapX;
this.drawY = this.coordY - SpaceMapY;
this.surfaceIMG = imgBluesky1;
this.isClicked = false;
this.locSurface = 0;
};
Planet.prototype.draw = function(){
this.drawX = this.coordX - SpaceMapX;
this.drawY = this.coordY - SpaceMapY;
ifClicked(this);
if(this.isClicked){
PlanetDiv.style.display = "block";
var LandPlanetDivButton = '<button id="LandPlanetDivButton" type="button" onclick="landOnSurface();">Land On Surface</button>';
var ClosePlanetDivButton = '<button id="ClosePlanetDivButton" type="button" onclick="ClosePlanetDiv();">Close (x)</button><br/><p id="PlanetDivText">' ;
PlanetDiv.style.zIndex = "2";
HideCanvas();
planetClicked = this;
PlanetDiv.innerHTML = LandPlanetDivButton + ClosePlanetDivButton + this.planetType; + '</p>';
}
ctxPlanets.drawImage(imgPlanets,this.srcX,this.srcY,this.srcW,this.srcH,this.drawX,this.drawY,this.w,this.h);
};
Planet.prototype.drawSurfaceImg = function(){
if(SurfaceMap2 >= 0) SurfaceMap2 = -1600;
if(SurfaceMap2 < -1600) SurfaceMap2 = -1;
if(SurfaceMap >= 1600) SurfaceMap = 0;
if(SurfaceMap < 0) SurfaceMap = 1599;
ctxSurface.drawImage(this.surfaceIMG, 0, 0, 1600, gameHeight, SurfaceMap, 0, 1600, gameHeight);
ctxSurface.drawImage(this.surfaceIMG, 0, 0, 1600, gameHeight, SurfaceMap2, 0, 1600, gameHeight);
};
//----------------------------- END OF PLANET OBJECT -----------------------------------
//-----end Objects
function randomFromTo(from,to){
return Math.floor(Math.random()*(to-from+1)+from);
};
function closestNum(Num, a){
var num = Num + (gameWidth/2);
var closest = a[0];
var difference = Math.abs (num - closest);
for (var i = 0; i < a.length; i++) {
var difference2 = Math.abs (num - a[i]);
if (difference2 < difference) {
difference = difference2;
closest = a[i];
}
}
return closest;
};
function sortNum(a)
{
var swapped;
do{
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
}while (swapped);
};
function ifClicked(obj){
if(mouseX >= obj.drawX && mouseX <= obj.drawX + obj.w){
if(mouseY >= obj.drawY && mouseY <= obj.drawY + obj.h){
obj.isClicked = true;
}
}
else{
obj.isClicked = false;
}
};
function clearCtx() {
ctxMain.clearRect(0,0,gameWidth,gameHeight);
ctxShip.clearRect(0,0,gameWidth,gameHeight);
ctxPlanets.clearRect(0,0,gameWidth,gameHeight);
ctxHUD.clearRect(0,0,gameWidth,gameHeight);
ctxSurface.clearRect(0,0,gameWidth,gameHeight);
};
function checkKeyDown(e){
var keyID = e.keyCode || e.which;
if(keyID === 38 || keyID === 87){ // up arrow or W key
Player1.isUpKey = true;
Player1.direction = "North";
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 39|| keyID === 68){ // right arrow or D key
Player1.isRightKey = true;
Player1.direction = "East"
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 40 || keyID === 83){ // down arrow or S key
Player1.isDownKey = true;
Player1.direction = "South";
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 37 || keyID === 65){ // left arrow or A key
Player1.isLeftKey = true;
Player1.direction = "West";
Player1.isMoving = true;
e.preventDefault();
}
};
function checkKeyUp(e){
var keyID = e.keyCode || e.which;
if(keyID === 38 || keyID === 87){ // up arrow or W key
Player1.isUpKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 39|| keyID === 68){ // right arrow or D key
Player1.isRightKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 40 || keyID === 83){ // down arrow or S key
Player1.isDownKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 37 || keyID === 65){ // left arrow or A key
Player1.isLeftKey = false;
Player1.isMoving = false;
e.preventDefault();
}
};
function clearMouse(){
mouseX = 10000;
mouseY = 10000;
};
function checkMouseDown(e) {
var mX = (e.clientX - (canvasMS.offsetLeft - canvasMS.scrollLeft));
var mY = (e.clientY - (canvasMS.offsetTop - canvasMS.scrollTop));
if(mX <= gameWidth && mX >= 0) mouseX = mX;
if(mY <= gameHeight && mY >= 0) mouseY = mY;
//mouseIsDown = true;
};
function checkMouseUp(e){
//mouseIsDown = false;
clearMouse();
};
function ClosePlanetDiv (){
PlanetDiv.style.zIndex = "-2";
PlanetDiv.innerHTML = "";
PlanetDiv.style.display = "none";
ShowCanvas();
};
function HideCanvas(){
canvasShip.style.marginTop = "-10000px";
canvasPlanets.style.marginTop = "-10000px";
};
function ShowCanvas(){
canvasShip.style.marginTop = "-500px";
canvasPlanets.style.marginTop = "-500px";
};
function landOnSurface(){
ClosePlanetDiv();
inSpace = false;
onSurface = true;
Player1.srcX = 0;
planetSurface();
canvasSurface.style.display = "block";
OrbitReturn.style.display = "block";
};
function ReturntoOrbit(){
OrbitReturn.style.display = "none";
canvasSurface.style.display = "none";
inSpace = true;
onSurface = false;
Loop();
};
<!doctype html>
<html lang='en'>
<head>
<meta charset="utf-8">
<title>Space Explorer</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="Functions.js"></script>
</head>
<body>
<canvas id="MainScreen_cvs" width="800" height="500"></canvas>
<div id="PlanetDiv"></div>
<canvas id="Surface_cvs" width="800" height="500"></canvas>
<canvas id="Ship_cvs" width="800" height="500"></canvas>
<canvas id="Planets_cvs" width="800" height="500"></canvas>
<canvas id="HUD_cvs" width="800" height="500"></canvas>
<div id="OrbitReturn"></div>
<div id="log">
<h1 style="color:blue;">Recent updates will be logged here when made live.</h1>
<hr />
<h3> Wednesday August 3, 2016 </h3>
<ul>
<li> HTML file completed. Working on getting JS files started.</li>
<li> JS files created. </li>
<li>Basic ship & flight functions in place. Basic star map initialized.</li>
</ul>
<hr />
</div>
<script type="text/javascript" src="game.js"></script>
</body>
</html>
body {
background: #303030;
}
#MainScreen_cvs {
position: relative;
display: block;
background: #777777 ;
margin: 30px auto 0px;
z-index: 1;
}
#Surface_cvs{
position: relative;
display: none;
z-index: 1;
margin: -500px auto 0px;
}
#Ship_cvs, #Planets_cvs, #HUD_cvs {
display: block;
position: relative;
margin: -500px auto 0px;
z-index: 1;
}
#log {
display: block;
position: absolute;
top: 560px;
left: 233px;
background: #ffffff;
overflow: scroll;
width: 800px;
height: 300px;
z-index: 3;
}
#OrbitReturn{
display: block;
position: relative;
width: 800px;
height: 500px;
z-index: 3;
margin: -500px auto 0px;
}
#PlanetDiv {
display: block;
position: relative;
width: 800px;
height: 500px;
background-image: url("images/Sky.jpg");
z-index: -2;
margin: -500px auto 0px;
}
#ClosePlanetDivButton{
float: right;
}
#LandPlanetDivButton{
position: absolute;
top: 400px;
left: 325px;
font-size: 20px;
}
#PlanetDivText{
text-indent: 50px;
font-size: 20px;
}
Something is happening with Ship.prototype.checkPos. Each time you land on the planet, it looks like the checking pauses, then starts up when you enter orbit. But this time he checkPos is getting called faster.
I could keep staring at it but you might be able to figure it out from there. I put a console.log('checkPos') at the top of that function and watched it pause and restart.
Ship.prototype.checkPos = function(PlanetX) {
console.log('checkPos');
if (inSpace) {
...
I think it might be here
function ReturntoOrbit() {
OrbitReturn.style.display = "none";
canvasSurface.style.display = "none";
inSpace = true;
onSurface = false;
//Loop(); <--- this little guy. Get rid of him.
};
I doing elements dragging possibility in my page.
User should drag any element with % or px set position.
The dragging of px positioned elements works good, but the dragging of % positioned elements is too fast and element runs away from mouse.
Which way I can fix this? I think I probably need to do some calculations, so the element will not move until mouse has run some distance, but I don't understand what exactly calculations I should make. This probably should be dependent from how much pixels in 1%.
<html style="height: 100%;">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>test export</title>
<script type='text/javascript'>
var curr_moving_elem;
var last_x, last_y;
function getIndexOfFirstNonDigitSymbolInString(str) {
if (!str)
return -1;
var index = -1;
for (var i = 0; i < str.length; i++)
if (str[i] != '-' && (str[i] < '0' || str[i] > '9')) {
index = i;
break;
}
return index;
}
function getIntegerFromAnyHTMLValue(str_val) {
int_val = 0;
var first_non_digit = getIndexOfFirstNonDigitSymbolInString(str_val);
if (first_non_digit < 0)
return NaN;
var digits_only = str_val.substring(0, first_non_digit);
return Number(digits_only);
}
function getStrSuffixFromAnyHTMLValue(str_val, suffix) {
suffix = "";
var first_non_digit = getIndexOfFirstNonDigitSymbolInString(str_val);
if (first_non_digit < 0)
return "";
return str_val.substring(first_non_digit);
}
function handleMouseDown(e) {
if (e.button == 0) {
var main_elem_under_mouse = getMainElemUnderMouseClickOrDownOrMoveOrUp(e);
if (main_elem_under_mouse && (main_elem_under_mouse.style.position.toLowerCase() == "absolute" || main_elem_under_mouse.style.position.toLowerCase() == "relative" || main_elem_under_mouse.style.position.toLowerCase() == "fixed")) {
curr_moving_elem = main_elem_under_mouse;
last_x = e.x;
last_y = e.y;
}
}
}
function handleMouseMove(e) {
if (curr_moving_elem && e.button == 0) {
var curr_top = curr_moving_elem.style.top;
var curr_left = curr_moving_elem.style.left;
var int_top = getIntegerFromAnyHTMLValue(curr_top);
var top_suffix = getStrSuffixFromAnyHTMLValue(curr_top);
var int_left = getIntegerFromAnyHTMLValue(curr_left);
var left_suffix = getStrSuffixFromAnyHTMLValue(curr_left);
var new_top = (int_top + (e.y - last_y)) + top_suffix;
curr_moving_elem.style.top = new_top;
var new_left = (int_left + (e.x - last_x)) + left_suffix;
curr_moving_elem.style.left = new_left;
last_x = e.x;
last_y = e.y;
}
}
function handleMouseUp(e) {
//if (e.button == 0)
//{
curr_moving_elem = null;
last_x = null;
last_y = null;
//}
}
function getMainElemUnderMouseClickOrDownOrMoveOrUp(e) {
var elem;
var evt = e || window.event;
if (!evt)
return null;
if (evt.target)
elem = evt.target;
else if (evt.srcElement)
elem = evt.srcElement;
if (elem && elem.nodeType == 3) // defeat Safari bug
elem = elem.parentNode;
if (elem)
if (elem.getAttribute('data-mainElem'))
return elem;
else {
var parent = elem.parentElement;
while (parent && !parent.getAttribute('data-mainElem'))
parent = parent.parentElement;
if (parent && parent.getAttribute('data-mainElem'))
return parent;
}
}
</script>
</head>
<body style="height: 100%; margin: 0px;" onmousedown="handleMouseDown(event);" onmousemove="handleMouseMove(event);"
onmouseup="handleMouseUp(event);">
<div data-mainelem='true' id='Div_107' style="position: ABSOLUTE; height: 20%; width: 35%;
top: 10px; left: 5px; background-color: #800000; background-position: left top;
background-repeat: repeat;">
</div>
<div data-mainelem='true' id='Div_108' style="position: ABSOLUTE; height: 40%; width: 25%;
top: 10%; left: 5%; background-color: #00FF00; background-position: left top;
background-repeat: repeat;">
</div>
</body>
</html>
I think your problem is here: e.x - last_x. This will return distance of mouse in pixel, but you need it in percentage. What you would need to to is set this to percentage of screen. Something like:
var percent_x = ((e.x - last.x)/window.innerWidth)*100
But then you'll have to differentiate between percentage or pixel.