var circle = document.getElementById("circle");
function moveUp() {
var top = circle.offsetTop;
newTop = top - 10;
circle.style.top = newTop + "px";
console.log("moveUP Called")
}
function moveDown() {
var top = circle.offsetTop;
newTop = top + 10;
circle.style.top = newTop + "px";
console.log("moveDown Called")
}
function moveLeft() {
var left = circle.offsetLeft;
newLeft = left - 10;
circle.style.left = newLeft + "px";
console.log("moveLeft Called")
}
function moveRight() {
var left = circle.offsetLeft;
newLeft = left + 10;
circle.style.left = newLeft + "px";
console.log("moveRight Called")
}
window.addEventListener("keypress", (event) => {
if (event.key == 'w') {
moveUp();
} else if (event.key == 's') {
moveDown();
} else if (event.key == 'a') {
moveLeft();
} else if (event.key == 'd') {
moveRight();
}
})
body {
margin: 2px;
background-color: aquamarine;
}
#circle {
height: 100px;
width: 100px;
background-color: blue;
border-radius: 50%;
position: absolute;
}
In the above code where on key press circle moves, for example on 'w' it moves up, for 's' it moves down and so on.
But the problem is that the circle even moves out of the window, how do I fix it and what is the problem??
var circle = document.getElementById("circle");
console.log(window.innerWidth, window.innerHeight)
function moveUp() {
var top = circle.offsetTop;
console.log(top)
newTop = top - 10;
if(newTop < 0) {
newTop = 0;
}
circle.style.top = newTop + "px";
}
function moveDown() {
var top = circle.offsetTop;
var height = circle.offsetHeight + top;
if((height + 10) >= window.innerHeight) {
return;
}
newTop = top + 10;
circle.style.top = newTop + "px";
/* console.log("moveDown Called") */
}
function moveLeft() {
var left = circle.offsetLeft;
newLeft = left - 10;
if(newLeft<0) {
newLeft = 0;
}
circle.style.left = newLeft + "px";
}
function moveRight() {
var left = circle.offsetLeft;
newLeft = left + 10;
if(newLeft > window.innerWidth - 100 ) {
newLeft = window.innerWidth - 100 ;
}
circle.style.left = newLeft + "px";
}
window.addEventListener("keypress", (event) => {
if (event.key == 'w') {
moveUp();
} else if (event.key == 's') {
moveDown();
} else if (event.key == 'a') {
moveLeft();
} else if (event.key == 'd') {
moveRight();
}
})
body{
margin:2px;
background-color: aquamarine;
}
#circle{
height: 100px;
width: 100px;
background-color: blue;
border-radius: 50%;
position: absolute;
overflow: hidden;
}
<div id="circle">
</div>
Explaination
for moveup() if the position is a negative number that means the div is going out of the viewport. So with the if condition new position will be always set to 0 preventing the div to go negative position.
for moveDown() first you get the offsetTop which means how far is the box from top position along with the offsetHeight which represents the height of the box. So add these two to get the total height. Now simply check if this height is going over the innerHeight + the distance(10) you are going with each move. If it is more than the innerHeight simply return. otherwise move the box.
moveLeft() is same as moveUp().
moveRight() is also same as moveDown() but here we're calculating the innerWidth. Subtract it with the box width so it doesn't go outside the viewport. Now simple condition check and set the new right position.
hope it helped
What is the problem?
There is no problem. CSS does exactly what you told it to do.
For example, you can click on 'w' couple of times, which will set left property for your absolutely positioned circle to, let's say, -160px. This will instruct the browser to move your element to the left, away from the viewport, i.e. to position it -160px of the left edge of the initial containing block or nearest positioned ancestor. More about left property: https://developer.mozilla.org/en-US/docs/Web/CSS/left
I would not say that it is a problem, because it is exactly what left is used for - move elements to whatever position you like. Sometimes you can hide elements by setting their position: absolute; left: -10000px;
How do I fix it?
If you don't want your circle to move away from the viewport, you need to check if your circle is 'touching' the viewport. I will use example with the left, but the same logic can be applied to top, right and bottom.
So for the left, this will consist of two parts:
Check what is the initial distance from your circle to the left edge of the viewport.
Check if absolute value of your new left value is not greater than this distance.
For example, for the left method:
var elDistanceToLeft = window.pageXOffset + circle.getBoundingClientRect().left;
function moveLeft() {
let left = circle.offsetLeft;
newLeft = Math.abs(left - 10) <= elDistanceToLeft ? left - 10 : -elDistanceToLeft;
circle.style.left = newLeft + "px";
}
In this case your circle will move all way to the left (on pressing 'a') until it 'touches' the viewport (screen). Then it will stop.
Here is a code snippet
var elDistanceToLeft = window.pageXOffset + circle.getBoundingClientRect().left
function moveLeft() {
let left = circle.offsetLeft;
newLeft = Math.abs(left - 10) <= elDistanceToLeft ? left - 10 : -elDistanceToLeft;
circle.style.left = newLeft + "px";
}
window.addEventListener("keypress", (ev) => { if (ev.key == 'a') { moveLeft();} })
#circle {
height: 100px;
width: 100px;
background-color: blue;
border-radius: 50%;
position: absolute;
}
#parent {
position: relative;
padding: 200px;
}
<div id="parent">
<div id="circle"></div>
</div>
Related
A previous QUESTION I had has led me to construct the code below. What Im trying to do is increment the element up/down/left/right based on keyboard arrow selection
"<div id="test"></div>"
by 20 pixels (or however many I chose) at a time. I have the "left" and "right" direction working for the most part but something interesting keeps happening when I try and change directions. First off whichever direction I initially chose to go first does not work on the first key press, I have to hit the arrow key of either left or right twice to start transitioning. Then once the transitions do start working; if im traveling left and then want to change direction to the right; it goes left even though im hitting the right key at least once before it goes the correct direction corresponding to the key I chose. This is a bit difficult to explain by text so here is the code pen so you can see what I mean. CODEPEN (hit the left and right arrow keys a couple times so clearly see the issue)
Also the functions moveDown() and moveUp() dont even move the box positioning at all. To try and trouble shoot the problem I added console.log('moveUp') and console.log('moveDown') in order to see whether the console was recognizing the key code when I struck it, and it clearly does. It even recognizes when I strike the left or right key but still runs the incorrect direction at-least once before it starts going the correct direction on the left and right keys.
I have a feeling it make have to do with transitions not being cleared or maybe using an IF statement might not be the base way to read the key code?
Also thought about using switch case for JavaScript key code recognition but I am pretty sure the issue would still be the same and im not skilled enough to pull off switchcase yet.
ALL I WANT is the box to go the direction I tell it to go using the arrows on my keypad, I am close but as you can see I am missing some key concepts
document.addEventListener("keydown", keyBoardInput);
var left = 0;
var top = 0;
function moveUp() {
console.log('moveUp');
document.getElementById("test").style.top = top + "px";
top -= 20;
document.getElementById("test").style.transition = "all 1s";
};
function moveDown() {
console.log('moveDown');
document.getElementById("test").style.top = top + "px";
top += 20;
document.getElementById("test").style.transition = "all 1s";
};
function moveLeft() {
console.log('moveLeft');
document.getElementById("test").style.left = left + "px";
left -= 20;
document.getElementById("test").style.transition = "all 1s";
};
function moveRight() {
console.log('moveRight');
document.getElementById("test").style.left = left + "px";
left += 20;
document.getElementById("test").style.transition = "all 1s";
};
function keyBoardInput() {
var i = event.keyCode;
if (i == 38) {
moveUp()
};
if (i == 40) {
moveDown()
};
if (i == 37) {
moveLeft()
};
if (i == 39) {
moveRight()
};
};
#test {
position: relative;
width: 30px;
border: 1px solid blue;
height: 10px;
top: 0px;
left: 0px;
}
<div id="test"></div>
2 issues: You updated your globals too late, just do it before you use it on the element. And the variable name "top" is reserved, just use another one (see this blog post). Here the code:
document.addEventListener("keydown", keyBoardInput);
var left = 0;
var topx = 0;
function moveUp() {
console.log('moveUp');
topx -= 20;
document.getElementById("test").style.top = topx + "px";
document.getElementById("test").style.transition = "all 1s";
};
function moveDown() {
console.log('moveDown');
topx += 20;
document.getElementById("test").style.top = topx + "px";
document.getElementById("test").style.transition = "all 1s";
};
function moveLeft() {
console.log('moveLeft');
left -= 20;
document.getElementById("test").style.left = left + "px";
document.getElementById("test").style.transition = "all 1s";
};
function moveRight() {
console.log('moveRight');
left += 20;
document.getElementById("test").style.left = left + "px";
document.getElementById("test").style.transition = "all 1s";
};
function keyBoardInput() {
var i = event.keyCode;
if (i == 38) {
moveUp()
};
if (i == 40) {
moveDown()
};
if (i == 37) {
moveLeft()
};
if (i == 39) {
moveRight()
};
};
#test {
position: relative;
width: 30px;
border: 1px solid blue;
height: 10px;
top: 0px;
left: 0px;
}
<div id="test"></div>
You need to do the arithmetic for top and left before setting it in the CSS :)
function moveUp() {
console.log('moveUp');
top -= 20;
document.getElementById("test").style.top = top + "px";
document.getElementById("test").style.transition = "all 1s";
};
function moveDown() {
console.log('moveDown');
top += 20;
document.getElementById("test").style.top = top + "px";
document.getElementById("test").style.transition = "all 1s";
};
function moveLeft() {
console.log('moveLeft');
left -= 20;
document.getElementById("test").style.left = left + "px";
document.getElementById("test").style.transition = "all 1s";
};
function moveRight() {
console.log('moveRight');
left += 20;
document.getElementById("test").style.left = left + "px";
document.getElementById("test").style.transition = "all 1s";
};
Here's a working fiddle: https://jsfiddle.net/x2yxexs9/
I have a div1 which animates background position on hover direction of mouse by jquery.
But it's working properly. it's going not right direction and I want it to work on every single mouse hover on the div.
Find jsfiddle
code:
$(function() {
$(".mainCont").hover(function(e) {
// $(this).addClass("hoverOnce");
var edge = closestEdge(e.pageX, e.pageY, $(this).width(), $(this).height());
}, function(){
$(this).removeClass('top right bottom left');
// $(this).removeClass("hoverOnce");
});
});
function closestEdge(x,y,w,h) {
var topEdgeDist = distMetric(x,y,w/2,0);
var bottomEdgeDist = distMetric(x,y,w/2,h);
var leftEdgeDist = distMetric(x,y,0,h/2);
var rightEdgeDist = distMetric(x,y,w,h/2);
var min = Math.min(topEdgeDist,bottomEdgeDist,leftEdgeDist,rightEdgeDist);
switch (min) {
case leftEdgeDist:
$(".hoverOnce").addClass("left");
case rightEdgeDist:
$(".hoverOnce").addClass("right");
case topEdgeDist:
$(".hoverOnce").addClass("top");
case bottomEdgeDist:
$(".hoverOnce").addClass("bottom");
}
}
function distMetric(x,y,x2,y2) {
var xDiff = x - x2;
var yDiff = y - y2;
return (xDiff * xDiff) + (yDiff * yDiff);
}
The size of this image that you use in the background is 700x500:
http://thesis2010.micadesign.org/kropp/images/research/bird_icon.png
I think that if you add these settings to .mainCont that this will get you the desired result:
width: 700px;
height: 500px;
position: absolute;
For example:
.mainCont {
width: 700px;
height: 500px;
background: url(http://thesis2010.micadesign.org/kropp/images/research/bird_icon.png) no-repeat center center;
transition: all 0.5s ease-in-out;
margin: 100px auto;
position: absolute;
}
Fiddle
Finally, It got solved.
find fiddle demo
$('.mainCont').hover(function(e){
var dir = determineDirection($(this), {x: e.pageX, y: e.pageY});
$(this).addClass('direction_'+dir);
}, function() {
$(this).removeClass('direction_3 direction_1 direction_2 direction_0');
});
function determineDirection($el, pos){
var w = $el.width(),
h = $el.height(),
x = (pos.x - $el.offset().left - (w/2)) * (w > h ? (h/w) : 1),
y = (pos.y - $el.offset().top - (h/2)) * (h > w ? (w/h) : 1);
return Math.round((((Math.atan2(y,x) * (180/Math.PI)) + 180)) / 90 + 3) % 4;
}
I'm trying to create my own click and drag function in JavaScript without the use of jquery. I know that jquery is easy to implement, but I prefer my own code. What I have, as i click the div, then move the mouse, the div moves to the same spot and doesn't implement a "dragging" look to it. I'm not sure why this is. I want my outcome to be able to move the div over the image that way I can "crop" the image based on the div, etc. My code is:
index.js
function _(element) {
return document.getElementById(element);
}
index.css
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgb(255,255,255);
position: absolute;
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8"/>
<title>Image Cropping</title>
<link rel = "stylesheet" href = "index.css"/>
<script src = "index.js"></script>
</head>
<body>
<div class = "image">
<img src = "model.jpg" alt = "Model" id = "theImage"/>
<div class = "selection" id = "selection"/>
</div>
<script>
_("theImage").ondragstart = function() { return false; };
var m = _("selection");
m.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
function mouseUp() {
window.removeEventListener("mousemove", move, true);
}
function mouseDown(e) {
window.addEventListener("mousemove", move, true);
}
function move(e) {
var x = m.style.left;
var y = m.style.top;
var mouseX = e.clientX;
var mouseY = e.clientY;
m.style.top += (mouseX - x) + "px";
m.style.left += (mouseY - y) + "px";
// Also tried: m.style.top = (mouseX - x) + "px";
// And : m.style.left = (mouseY - y) + "px";
}
</script>
</body>
</html>
To add the "dragging look to it", you can:
change the cursor (cursor: move;)
keep the cursor's offset relative to the mouse
For the second one, I reused a function I created for one of my projects, for which I implemented drag and drop for mobile, not wanting to use a big library:
/*
* Returns the given element's offset relative to the document.
*/
function realOffset(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return { top: top, left: left };
}
Using this function, the math becomes simple:
m.style.left = (mouseX - offset.left) + "px";
m.style.top = (mouseY - offset.top) + "px";
Full demo
_("theImage").ondragstart = function () { return false; };
var m = _("selection"), offset;
m.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
function mouseUp() { window.removeEventListener("mousemove", move, true); }
function mouseDown(e) {
// SAVE THE OFFSET HERE
offset = {
left: e.pageX - realOffset(m).left,
top: e.pageY - realOffset(m).top
};
window.addEventListener("mousemove", move, true);
}
function move(e) {
// REUSE THE OFFSET HERE
m.style.left = (e.pageX - offset.left) + "px";
m.style.top = (e.pageY - offset.top) + "px";
}
/*
* Returns the given element's offset relative to the document.
*/
function realOffset(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return { top: top, left: left };
}
function _(element) { return document.getElementById(element); }
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgba(255,255,255,.5);
position: absolute;
cursor: move;
}
<div class="image">
<img src="http://i.imgur.com/vxkljMP.jpg" alt="Model" id="theImage" />
<div class="selection" id="selection"></div>
</div>
I have a code which causes the waterlevel in a bottle to go up or down by clicking a button. however, it can't stop without clicking on stop. I need it to basically reset when it empties, and that the div of the waterlevel doesn't go below a certain point (or above a certain point). If you're interested in what I'm making; I'm making an alcohol simulator. So you'll basically see the waterlevel of an alcohol drink going down (i.e. 100 px), and 100 px down means that you can see the waterlevel(alcogol level) in the stomach with i.e. 50 px, and that equals 20 px in the blood circulation and 10 px in the brains. (just to get an idea.)
But if I click on the button of going down, the div will just leave the bottle and will have an endless journey. (js please, not jquery)
here's my JS code:
function move_img(str) {
var step=2 ; // change this to different step value
switch(str){
case "down":
var x=document.getElementById('i1').offsetTop;
x= x + step;
document.getElementById('i1').style.top= x - 1 + "px";
break;
case "up":
var x=document.getElementById('i1').offsetTop;
x= x -step;
document.getElementById('i1').style.top= x + "px";
break;
case "left":
var y=document.getElementById('i1').offsetLeft;
y= y - step;
document.getElementById('i1').style.left= y + "px";
break;
case "right":
var y=document.getElementById('i1').offsetLeft;
y= y + step;
document.getElementById('i1').style.left= y + "px";
break;
}
}
function auto(str) {
myVar = setInterval(function(){ move_img(str); }, 2) ;
}
setTimeout(function( ) { clearInterval( myVar ); }, 1);
function nana(){
}
Your fiddle doesn't work. You'll need to specify the height as well as the top attribute, and I believe top has to be above bottom. I've made an example here. The changes to your examples are:
//javascript
if (str == 'up' || str == 'down') {
var top = el.offsetTop;
var height = el.offsetHeight; //get height to modify
console.log(height);
if (str == 'up') {
top -= step;
height += step; //adjust height
} else {
top += step;
height -=step; //adjust height
}
if (top_max >= top && top >= 0) { //make sure #i1 is inside #i
document.getElementById('i1').style.top = top + "px";
document.getElementById('i1').style.height = height + "px"; //modify height
} else {
clearInterval(myVar)
}
//css
#i1 {
width: 100px;
display: inline-block;
background:red;
position: absolute;
top: 150px; //initial top
bottom: 250px; //as as bottom of #i
height:100px; //initial height
}
I have a dynamic div, and I want to know when the mouse is hover this div. I tryed with .is( ':hover' ) but doesn't work.
jsFiddle demo
In the demo I have made a moving div and if I doesn't move the mouse the log is never called, but if I put manually the mouse hover the box it write always the logs.
Never writes the log in the console.
Always writes the log in the console, even the box is gone.
It's a bug or I have made a mistake? How can I detect the hover properly?
You should be tracking the mouse movement with the mousemove() event and check the last known position of the mouse on the movement of the div.
Example:
HTML & CSS:
.red-box {
display : inline-block;
position : absolute;
width : 50px;
height : 50px;
top : 10px;
left : 0px;
background-color : red;
}
#wrapper {
height: 100vh;
width: 100vw;
}
<div id="wrapper">
<div class="red-box"></div>
</div>
JavaScript:
var posX = 0;
var step = 10;
var maxX = 200;
var mouseX = -1;
var mouseY = -1;
var entered = false;
var $box = $('.red-box');
setInterval(function () {
posX += step;
if (posX >= maxX)
posX = 0;
$box.css("left", posX);
var top = $box.offset().top;
if (mouseX >= posX && mouseX <= (posX + $box.width()) && mouseY >= top && mouseY <= (top + $box.height())) {
console.log("mouse entered");
entered = true;
} else if (entered) {
console.log("mouse left");
entered = false;
}
}, 500);
$("#wrapper").on("mousemove", function (e) {
mouseX = e.pageX - $(this).position().left;
mouseY = e.pageY - $(this).position().top;
}).on("mouseleave", function()
{
mouseX = -1;
mouseY = -1;
});
FIDDLE
Edit: Added a new mouseleave() event to the wrapper.