I now have a working touchscreen image slider but the only problem is that when I touchscreen the movement position begins from the center of the div and moves the whole div to be positioned with the pointer in the middle and lift off screen - and then attempt to do another movement. the movement position begins again in the center of the div.
I know I need to reset the co-ords somehow when I lift off screen, or maybe unbind, but I have no idea how to do this. It takes me days if not weeks to simply figure these things out without help. Don't get me wrong I'm all about learning for myself, but I also learn a great deal more where I can examine a working solution of my own code.
Here is a little HTML for the divs:
.container{
position:absolute;
top:0%;
left:0%;
width:500px;
height:100%;
}
.drag{
position: absolute;
top:1%;
left:0%;
width:100%;
height:15%;
-webkit-transform: translate3d(0,0,0);
border-style: solid; 2px;
border-color: blue;
z-index:1000;
}
</head>
<body>
<div id="container" class="container">
<div id='drag' class='drag'><!---video area--->
some images
</div>
</div>
Here is the code for the swipe events.
var dom = {
container: document.getElementById("container"),
drag: document.getElementById("drag"),
}
var container = {
x: dom.container.getBoundingClientRect().left,
y: dom.container.getBoundingClientRect().top,
w: dom.container.getBoundingClientRect().width,
h: dom.container.getBoundingClientRect().height
}
var drag = {
w: dom.drag.offsetWidth
}
target = null;
document.body.addEventListener('touchstart', handleTouchStart, false);
document.body.addEventListener('touchmove', handleTouchMove, false);
document.body.addEventListener('touchend', handleTouchEnd, false);
document.body.addEventListener('touchcancel', handleTouchCancel, false);
function handleTouchStart(e) {
if (e.touches.length == 1) {
var touch = e.touches[0];
target = touch.target;
}
}
function handleTouchMove(e) {
if (e.touches.length == 1) {
if(target === dom.drag) {
moveDrag(e);
}
}
}
function handleTouchEnd(e) {
if (e.touches.length == 0) { // User just took last finger off screen
target = null;
}
}
function handleTouchCancel(e) {
return;
}
function moveDrag(e) {
var touch = e.touches[0];
var posX = touch.pageX - container.x - drag.w / 2;
dom.drag.style.left = posX + "px";
}
I KNOW IT'S DOWN TO THIS LINE OF CODE:
var posX = touch.pageX - container.x - drag.w / 2;
HERE IS THE FIDDLE:
http://jsfiddle.net/xbmyazb2/20/
Related
I am trying to make a web app with two boxes, one contained in the other. The user should be able to click and move the inner box, however, the user should not be able to move this box outside the confines of the outer box. The user can move the outer box by dragging the inner box against one of the edges of the outer box. I know how to move the inner box, but the problem is how to move the other box with this restriction. Can anybody help me please? Here is what I did so far:
<!doctype html>
<head>
<title>JavaScript Game</title>
<style>
#container {
height:400px;
width:600px;
outline: 1px solid black;
position:absolute;
left:50px;
top: 0px;
background-color:green;
}
#guy {
position:absolute;
height:50px;
width:50px;
outline: 1px solid black;
background-color:red;
left: 200px;
top: 200px;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="guy"></div>
<script>
var guy=document.getElementById("guy");
var cont=document.getElementById("container");
var lastX,lastY; // Tracks the last observed mouse X and Y position
guy.addEventListener("mousedown", function(event) {
if (event.which == 1) {
lastX = event.pageX;
lastY = event.pageY;
addEventListener("mousemove", moved);
event.preventDefault(); // Prevent selection
}
});
function buttonPressed(event) {
if (event.buttons == null)
return event.which != 0;
else
return event.buttons != 0;
}
function moved(event) {
if (!buttonPressed(event)) {
removeEventListener("mousemove", moved);
} else {
var distX = event.pageX - lastX;
var distY = event.pageY - lastY;
guy.style.left =guy.offsetLeft + distX + "px";
guy.style.top = guy.offsetTop + distY + "px";
lastX = event.pageX;
lastY = event.pageY;
}
}
</script>
</body>
You could add a check to see if moving the box would break bounds of cont.
try to use getBoundingClientRect()
Check the snippet below for the working code.
View in full screen for best results.
var guy=document.getElementById("guy");
var cont=document.getElementById("container");
var lastX,lastY; // Tracks the last observed mouse X and Y position
guy.addEventListener("mousedown", function(event) {
if (event.which == 1) {
lastX = event.pageX;
lastY = event.pageY;
addEventListener("mousemove", moved);
event.preventDefault(); // Prevent selection
}
});
function buttonPressed(event) {
if (event.buttons == null)
return event.which != 0;
else
return event.buttons != 0;
}
function moved(event) {
if (!buttonPressed(event)) {
removeEventListener("mousemove", moved);
} else {
var distX = event.pageX - lastX;
var distY = event.pageY - lastY;
guy.style.left =guy.offsetLeft + distX + "px";
guy.style.top = guy.offsetTop + distY + "px";
// ********************************************************************
// get bounding box borders
var contBounds = guy.getBoundingClientRect();
var guyBounds = cont.getBoundingClientRect();
// check bottom bounds
if (contBounds.bottom >= guyBounds.bottom){
cont.style.top = cont.offsetTop + distY + "px";
}
// check top bounds
if (contBounds.top <= guyBounds.top){
cont.style.top = cont.offsetTop + distY + "px";
}
// check left bounds
if (contBounds.left <= guyBounds.left){
cont.style.left = cont.offsetLeft + distX + "px";
}
// check right bounds
if (contBounds.right >= guyBounds.right){
cont.style.left = cont.offsetLeft + distX + "px";
}
// ********************************************************************
lastX = event.pageX;
lastY = event.pageY;
}
}
#container {
height:300px;
width:300px;
outline: 1px solid black;
position:absolute;
left:50px;
top: 0px;
background-color:#CCC;
}
#guy {
position:absolute;
height:50px;
width:50px;
outline: 1px solid black;
background-color:#000;
left: 200px;
top: 200px;
}
<div id="container"></div>
<div id="guy"></div>
try this link to get you started as far as keeping the "guy" inside the "contatiner": http://www.w3schools.com/html/html5_draganddrop.asp
their example shows how you can make an element only drop inside another element.
as far as moving the container...i would think that you could add some if else statements into the moved function that will test the position of the guy against the conatiner's outline and say that when they meet to move the container as well.
i am very new to javascript myself but this is just a suggestion from what i think i understand of it.
I have a Javascript that I use to display a lightbox when a visitor's mouse breaks the browser plane... here's my page: [http://mudchallenger.com/index-test2.html][1]
However, if you move your mouse too fast, it does not recognize that you've left the page and the script does not fire.
Does anyone know how to modify this script so that it fires if the mouse is not present in the window?
Here's the script:
var oldPosition = -1;
$(document).ready(function() {
$(document).mousemove(function(e) {
$('#exitpopup').css('left', (window.innerWidth / 2 - $('#exitpopup').width() / 2));
$('#exitpopup').css('top', (window.innerHeight / 2 - $('#exitpopup').height() / 2));
var position = e.pageY - $(window).scrollTop();
if(position < 10) {
if(oldPosition != -1) {
if(position < oldPosition) {
// Show the exit popup
$('#exitpopup_bg').fadeIn();
$('#exitpopup').fadeIn();
}
oldPosition = position;
} else {
oldPosition = position;
}
}
$('#divData').html(oldPosition + " : " + position);
});
$('#exitpopup_bg').click(function() {
$('#exitpopup_bg').fadeOut();
$('#exitpopup').slideUp();
});
});
I include this tag in the .html page
<?php require('exitpopup.php'); ?>
Here is the 'exitpopup.php' script
<script type="text/javascript">
var oldPosition = -1;
$(document).ready(function() {
$(document).mousemove(function(e) {
$('#exitpopup').css('left', (window.innerWidth / 2 - $('#exitpopup').width() / 2));
$('#exitpopup').css('top', (window.innerHeight / 2 - $('#exitpopup').height() / 2));
var position = e.pageY - $(window).scrollTop();
if(position < 20) {
if(oldPosition != -1) {
if(position < oldPosition) {
// Show the exit popup
$('#exitpopup_bg').fadeIn();
$('#exitpopup').fadeIn();
}
oldPosition = position;
} else {
oldPosition = position;
}
}
$('#divData').html(oldPosition + " : " + position);
});
$('#exitpopup_bg').click(function() {
$('#exitpopup_bg').fadeOut();
$('#exitpopup').slideUp();
});
});
</script>
<style type="text/css">
#exitpopup
{
text-align:center;
}
#exitpopup h1
{
margin-top:0px;
padding-top:0px;
}
#exitpopup p
{
text-align:left;
}
</style>
<div style="display: none; width:100%; height:100%; position:fixed; background:#000000; opacity: .9; filter:alpha(opacity=0.9); z-index:999998;" id="exitpopup_bg">
</div>
<div style="width:975px; height:575px; margin:0px auto; display:none; position:fixed; color:#000000; padding:0px; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; z-index:999999; background-image: url(exit-gate/exit-gate-bg2.png);" id="exitpopup">
</div>
I think you're overcomplicating thing with positioning.
$('html').hover(
function() {
console.log('Entered browser window')
},
function() {
console.log('Left browser window')
}
)
Detects both enter/leave or use just .mouseleave() on 'html' to detect when mouse left. So in your case remove your entire $(document).mousemove handler and replace it with
$('html').mouseleave(function() {
$('#exitpopup_bg').fadeIn();
$('#exitpopup').fadeIn();
})
Add left/top positioning of the popup as needed, but ideally it should be in CSS only
I'm trying to implement drag and drop for Mobile Safari.
Basically I want to drag a div via touch while it plays a looping CSS animation. I also want to determine when it's above a drop target and do something special.
I'm using elementFromPoint to determine what elements my div is being dragged over on touchmove events. However, the dragged div is always the topmost element. So before querying, I set it to display: none. However, this has the effect of resetting my animation every frame in which the touch moves.
How do I determine what I'm dragging above without resetting my CSS animation every time I query?
JSFiddle using touch events in WebKit.
HTML On every touchmove I move the drag div.
<div id='drop'>Drop here</div>
<div id='drag'>Drag me</div>
JavaScript
var drag = document.getElementById('drag');
var drop = document.getElementById('drop');
drag.addEventListener('touchmove', move, true);
function move(e) {
var touch = e.changedTouches[0];
drag.style.left = touch.pageX - 25 + 'px';
drag.style.top = touch.pageY - 25 + 'px';
drag.style.display = 'none';
if (drop === document.elementFromPoint(touch.pageX, touch.pageY)) {
drag.classList.add('in-drop-zone');
} else {
drag.classList.remove('in-drop-zone');
}
drag.style.display = 'inline';
}
CSS
div {
position: absolute;
}
div#drag {
width: 50px;
height: 50px;
background-color: blue;
-webkit-transform-origin: 50% 50%;
-webkit-animation: sway 1s infinite alternate;
}
div#drop {
width: 100px;
height: 100px;
background-color: green;
left: 200px;
top: 200px;
}
div#drag.in-drop-zone {
background-color: yellow;
}
#-webkit-keyframes sway {
from {
-webkit-transform: rotate(-30deg);
}
to {
-webkit-transform: rotate(30deg);
}
}
You could probably set pointer-events: none and then pointer-events: auto, but that seems pretty hacky. A better option is to have an intersection function:
var drag = document.getElementById('drag');
var drop = document.getElementById('drop');
var drop_bbox = drop.getBoundingClientRect();
window.addEventListener('touchmove', move, true);
window.addEventListener('mousemove', move, true);
function move(e) {
drag.style.left = e.clientX - 25 + 'px';
drag.style.top = e.clientY - 25 + 'px';
var drag_bbox = e.target.getBoundingClientRect();
drag.className = rectsIntersect(drag_bbox, drop_bbox) ? "in-drop-zone" : null;
}
function rectsIntersect(r1, r2) {
if (!r1 || !r2) return false;
return r2.left < (r1.left+r1.width) &&
(r2.left+r2.width) > r1.left &&
r2.top < (r1.top+r1.height) &&
(r2.top+r2.height) > r1.top;
};
Here is a JSFiddle http://jsfiddle.net/duopixel/SvPpw/
Is there a way to make this script switch images based on the direction the pointer is?
For example, if you have a fish, and you move the mouse to the right of the fish, it switches to an image facing that way. When you move your pointer to the left of the fish, it points it the other way.
demo
JAVASCRIPT
$("#foo").mousemove(function(event) {
$("#bee1").stop().animate({left: event.pageX, top: event.pageY}, 300)
});
HTML
<div id="foo">
<div id="bee1">MoveMe</div>
</div>
CSS
#foo{
height:500px;
width:400px;
}
#bee1{
position:absolute;
border:1px solid #ccc;
}
$("#foo").mousemove(function(event) {
var bee = $("#bee1");
var position = bee.position();
var mousey = event.pageX;
if(position.left > mousey) {
$("#bee1").html("left");
} else {
$("#bee1").html("right");
}
$("#bee1").stop().animate({left: event.pageX, top: event.pageY}, 300);
});
Just check if current mouse position x is greater than image position and change your image src accordingly:
$("#foo").mousemove(function(event) {
var mousePos = {x: event.pageX, y: event.pageY},
elPos = imgEl.offset();
if(mousePos.x > elPos.left){
direction = '-->';
}
else{
direction = '<--';
}
imgEl.text(direction);
imgEl.stop().animate({left: event.pageX, top: event.pageY}, 300)
});
http://jsfiddle.net/WfQwZ/
I need a rocket to follow the movements of the mouse pointer on my website. This means it should rotate to face the direction of motion, and if possible, accelerate depending on the distance it has to cover.
Is this even possible ? jquery perhaps ?
by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.
example as below
http://jsfiddle.net/BfLAh/1/
$(document).mousemove(function(e) {
$("#follow").css({
left: e.pageX,
top: e.pageY
});
});
#follow {
position: absolute;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
updated to follow slowly
http://jsfiddle.net/BfLAh/3/
for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
for the speed , you can set the jquery .animation duration to certain amount.
Ok, here's a simple box that follows the cursor
Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.
Select the right image (use a sprite) to orientate the rocket.
Yeah, annoying as hell. :-)
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '1px solid red';
s.textContent = "🚀"
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<div id="container"></div>
Here's my code (not optimized but a full working example):
<head>
<style>
#divtoshow {position:absolute;display:none;color:white;background-color:black}
#onme {width:150px;height:80px;background-color:yellow;cursor:pointer}
</style>
<script type="text/javascript">
var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
var offX = 15; // X offset from mouse position
var offY = 15; // Y offset from mouse position
function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}
function follow(evt) {
var obj = document.getElementById(divName).style;
obj.left = (parseInt(mouseX(evt))+offX) + 'px';
obj.top = (parseInt(mouseY(evt))+offY) + 'px';
}
document.onmousemove = follow;
</script>
</head>
<body>
<div id="divtoshow">test</div>
<br><br>
<div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>Mouse over this</div>
</body>