dragging behaving strangely - javascript

i created a red div.Using mouse cursor i can move it anywhere on the screen.it was fine and smooth.then i decided to add an extra orange div inside the red div.i made the positioning "absolute" for the red div and "relative" for the orange div.as soon as i put the orange div inside the red div the position changing is not smooth .if i click on the orange portion an then move it is smooth but if i clip the visible red portion and move my mouse it is not smooth.how to fix this..
JSfiddle
<html>
<head>
<style>
* {
margin: 0px;
padding: 0px;
}
#mydiv {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
top: 300px;
left: 200px;
}
#mid {
position: relative;
width: 40px;
height: 40px;
margin: 30px 30px;
background-color: orange;
}
</style>
</head>
<body>
<div id="mydiv">
<div id="mid"></div>
</div>
<script>
var gotit = false;
var i, p, q;
var divs = document.getElementById("mydiv");
divs.addEventListener('mousedown', clipit, false);
divs.addEventListener('mousemove', function (e) {
moveit(e);
}, false);
divs.addEventListener('mouseup', unclip, false);
divs.addEventListener('mouseout', unclip, false);
function clipit() {
i = divs.offsetLeft;
gotit = true;
p = e.clientX;
q = e.clientY;
}
function moveit(e) {
if (gotit == true) {
if (e.clientX > divs.offsetLeft) {
divs.style.left = divs.offsetLeft + (e.clientX - p) + "px";
p = e.clientX;
}
if (e.clientY > divs.offsetTop) {
divs.style.top = divs.offsetTop + (e.clientY - q) + "px";
q = e.clientY;
}
}
}
function unclip() {
gotit = false;
}
</script>
</body>
</html>

You forgot to put the event in clipit:
function clipit(e) {}
Remember to always check your console log:
Uncaught ReferenceError: e is not defined
fix

Related

How to drag or move a span into the Div by using javascript

How to move or drag the span into the Div element. My element structure is the Div -> Span. Here I need to drag the Span inside the div element without drag beyond that div. I have tried this by calculating pixels but didn't give a solution. I don't need a native onDrag method.
I need to calculate pixels and drag the Span inside the Div. Here is my code.
var handleClick = false;
window.dragging = function(event) {
if (handleClick) {
var bar = document.getElementsByClassName('bar')[0],
handle = document.getElementsByClassName('handle')[0];
var left = bar.offsetWidth - handle.offsetWidth;
tops = (bar.offsetWidth - handle.offsetWidth);
pixel = left < ((pixel - 0) / 1.233445) ? left : ((pixel - 0) / 1.233445);
handle.style.left = pixel + "px";
}
}
document.addEventListener('mouseup', function() {
handleClick = false;
});
window.handlersDown = function() {
handleClick = true;
}
.bar {
width: 100px;
height: 30px;
border: 1px solid;
position: relative;
}
.handle {
width: 20px;
height: 20px;
left: 2px;
top: 5px;
background-color: rgba(255, 0, 0, 0.5);
position: absolute;
}
<div class="bar">
<span class="handle" onmousedown="handlersDown()" onmousemove="dragging(event)"></span>
</div>
I have modified your code a bit and changed the selectors from class to ID. I also would advice you to use external libraries to make it more easy for you. Besides that I also removed the event listeners inside your HTML and translate them to Javascript. Is this what you want?
window.onload = addListeners();
function addListeners(){
document.getElementById('handle').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp()
{
window.removeEventListener('mousemove', spanMove, true);
}
function mouseDown(e){
window.addEventListener('mousemove', spanMove, true);
}
function spanMove(e){
var bar = document.getElementById('bar')
var span = document.getElementById('handle');
// variables
var bar_width = bar.offsetWidth;
var handle_width = span.offsetWidth;
// stop scroll left if the minimum and maximum is reached
if(e.clientX < bar_width - handle_width - 1 && e.clientX > 1){
span.style.left = e.clientX + 'px';
}
}
#bar {
width: 100px;
height: 30px;
border: 1px solid;
position: relative;
}
#handle {
width: 20px;
height: 20px;
left: 2px;
top: 5px;
background-color: rgba(255, 0, 0, 0.5);
position: absolute;
}
<div id="bar">
<span id="handle"></span>
</div>
In 2020, following solution works perfectly on last version of Chrome, Opera, Firefox and Edge Chromium.
window.onload = addListeners();
function addListeners()
{
var div = document.getElementById('div');
var span = document.getElementById('span');
span.addEventListener('mousedown', onMouseDown, false);
window.addEventListener('mouseup', onMouseUp, false);
//compute space between left border of <div> and left border of <span>
// this value is also used to compute space at right
iMinLeft = span.offsetLeft;
// compute max left value allowed so that span remains in <div>
iMaxLeft = div.clientWidth - span.offsetWidth - iMinLeft;
}
function onMouseDown(e)
{
if (e.which === 1) // left button is pressed
{
e.preventDefault();
window.addEventListener('mousemove', onMouseMove, true);
// save mouse X position to compute deplacement
posMouseX = e.clientX;
span.style.background = "yellow";
}
}
function onMouseMove(e)
{
e.preventDefault();
//compute mouse deplacement
deltaX = posMouseX - e.clientX;
//compute new left position of <span> element
iNewLeft = span.offsetLeft - deltaX;
if (iNewLeft < iMinLeft)
{
iNewLeft = iMinLeft;
}
else
{
if (iNewLeft > iMaxLeft)
{
iNewLeft = iMaxLeft;
}
}
span.style.left = iNewLeft + 'px';
// save mouse X position to compute NEXT deplacement
posMouseX = e.clientX;
}
function onMouseUp(e)
{
if (e.which === 1) // left button is pressed
{
e.preventDefault();
span.style.background = "white";
window.removeEventListener('mousemove', onMouseMove, true);
}
}
#div
{
width: 200px;
height: 50px;
border: 1px solid;
position: relative;
left: 50px;
}
#span
{
cursor: pointer;
font-size: 30px;
width: auto;
height: 40px;
left: 2px;
top: 5px;
position: absolute;
}
<div id="div">
<span id="span">&#x1F603</span>
</div>
JavaScript line e.preventDefault(); is necessary to avoid <span> to become 'blue' when dragging.
CSS code cursor: pointer; is only to see that unicode is clickable.
Javascript line if (e.which === 1) has been added to prevent emoticon to move when RIGHT mouse button is clicked.
The rectangle around emoticon when <span> is dragged move without being shifted (see previous solution) and space remaining in left or in right are equal.
Thanks to w3schools-exemple

JavaScript script that only work on chrome, not working in Firefox. (Script for dragging div)

May be this is small question. But I couldn't found reason for this. I made a script to change a position of div by dragging it. the code is working fine with chrome browser. but when I trying to test it on Firefox it is not working.
var h = window.innerHeight|| document.documentElement.clientHeight || document.body.clientHeight;
window.onload = function () {
// ------------------lock the div with mouse pointer--------------
// variable dragged is for identified that you are click on the button or not
var dragged = false,
y = 0,pointerDis = 0,
boxElement = document.getElementById('drag'),
drgElement = document.getElementById('titl');
if (boxElement) {
// -----------------check whether the title div is holding by the mouse to lock it with mouse-------
drgElement.addEventListener('mousedown', function() {
dragged = true;
pointerDis = event.clientY - parseInt(window.getComputedStyle(boxElement, null).getPropertyValue("top"));
});
//------------------check whether the title div is released to drop the div-------------------------
document.addEventListener('mouseup', function() {
dragged = false;
});
document.addEventListener('mousemove', function () {
y = event.clientY;
if(dragged == true)
{
y = y -pointerDis;
if(y<0)
{
y = 0;
}
else if(y > window.innerHeight - boxElement.offsetHeight)
{
y = window.innerHeight - boxElement.offsetHeight;
}
boxElement.style.top = y + 'px';
}
});
}
};
.drg {
position: absolute;
top:0;
right: 0;
background: red;
border-top-left-radius: 45px;
border-bottom-left-radius: 45px;
}
#titl{
background: blue;
width: 50px;
text-align: center;
color: white;
font-size: 30px;
border-top-left-radius: 10px;
}
#det{
background: #f9c500;
width: 50px;
border-bottom-left-radius: 10px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>test 4</title>
</head>
<body>
<div class = "drg" id="drag">
<div id="titl" unselectable="on" onselectstart="return false;">....</div>
<div id="det">this is the details menu</div>
</div>
</body>
</html>
You can drag it through Y axis by click and drag from blue div. I don't know the reason or I couldn't find a way to fix this work on Firefox. Please help me!
You have to catch the (mousemove or mousedown) events as the input of wrapped functions
drgElement.addEventListener('mousedown', function(event)...
var h = window.innerHeight|| document.documentElement.clientHeight || document.body.clientHeight;
window.onload = function () {
// ------------------lock the div with mouse pointer--------------
// variable dragged is for identified that you are click on the button or not
var dragged = false,
y = 0,pointerDis = 0,
boxElement = document.getElementById('drag'),
drgElement = document.getElementById('titl');
if (boxElement) {
// -----------------check whether the title div is holding by the mouse to lock it with mouse-------
drgElement.addEventListener('mousedown', function(event) {
dragged = true;
pointerDis = event.clientY - parseInt(window.getComputedStyle(boxElement, null).getPropertyValue("top"));
});
//------------------check whether the title div is released to drop the div-------------------------
document.addEventListener('mouseup', function() {
dragged = false;
});
document.addEventListener('mousemove', function (event) {
y = event.clientY;
if(dragged == true)
{
y = y -pointerDis;
if(y<0)
{
y = 0;
}
else if(y > window.innerHeight - boxElement.offsetHeight)
{
y = window.innerHeight - boxElement.offsetHeight;
}
boxElement.style.top = y + 'px';
}
});
}
};
.drg {
position: absolute;
top:0;
right: 0;
background: red;
border-top-left-radius: 45px;
border-bottom-left-radius: 45px;
}
#titl{
background: blue;
width: 50px;
text-align: center;
color: white;
font-size: 30px;
border-top-left-radius: 10px;
}
#det{
background: #f9c500;
width: 50px;
border-bottom-left-radius: 10px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>test 4</title>
</head>
<body>
<div class = "drg" id="drag">
<div id="titl" unselectable="on" onselectstart="return false;">....</div>
<div id="det">this is the details menu</div>
</div>
</body>
</html>

Resize and rearrange divs through drag & drop and dynamic CSS

I have two divs that I want my users to be able to hit a button and arrange these two divs top/down or left/right. I have implemented it but whenever I arrange them left/right, the right div often overflows to the bottom of the left div.
I have seen another similar example that talks about resizing left/right divs, but I still don't know what exactly caused my right div to overflow. Any help is appreciated!
Here is my example:
var d = $('#divider'); // divider between top and bottom divs
var t = $('#tl'); // top/left div
var b = $('#br'); // bottom/right div
var h = $('body').height();
var w = $('body').width();
var isDragging = false;
var isLandscape = false;
d.mousedown(function(e) {
isDragging = true;
});
$(document).mouseup(function() {
isDragging = false;
}).mousemove(function(e) {
if (isDragging) {
if (!isLandscape) {
t.css('height', e.pageY);
b.css('height', h - e.pageY - d.height());
d.css('height', h - t.height() - b.height());
} else {
t.css('width', e.pageX);
b.css('width', w - e.pageX - d.width());
d.css('width', w - t.width() - b.width());
}
}
});
var rotateBtn = document.getElementById('rotateScreen');
if (rotateBtn) {
rotateBtn.addEventListener('click', rotateDisplay, false);
} else {
throw error;
}
function rotateDisplay() {
if (!isLandscape) {
isLandscape = true;
t.css('height', h);
t.css('width', Math.round(0.75 * w));
b.css('height', h);
b.css('width', Math.round(0.24 * w));
d.css('height', h);
d.css('width', w - t.width() - b.width());
d.css('cursor', 'w-resize');
} else {
isLandscape = false;
t.css('height', Math.round(0.75 * h));
t.css('width', w);
t.css('float', 'left');
b.css('height', Math.round(0.24 * h));
b.css('width', w);
b.css('float', 'left');
d.css('height', h - t.height() - b.height());
d.css('width', w);
d.css('cursor', 'n-resize');
d.css('float', 'left');
}
}
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#br {
width: 100%;
height: 24%;
float: left;
background: gold;
}
#tl {
width: 100%;
height: 75%;
float: left;
background: navy;
}
#divider {
height: 1%;
background: #fff;
float: left;
width: 100%;
cursor: ns-resize;
}
#control {
position: absolute;
z-index: 5;
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="control">
<button id="rotateScreen">🔁</button>
</div>
<div id="tl">This is the top/left div</div>
<div id="divider"></div>
<div id="br">This is the bottom/right div</div>

Whats wrong with my JavaScript animation?

So i have this web-page to design and i want an image of the moon to rise-up from bottom of the screen to top. This is the HTML :
<body>
<div id="Moon" onload="Moon()"></div>
</body>
CSS :
#Moon{
width: 150px;
height: 150px;
left: 50px;
top: 600px;
background: transparent url(../Img/Moon.SVG) no-repeat ;
position: absolute;
}
and JavaScript for animation :
function Moon(){
var Moon=document.getElementById("Moon");
var yposition=Moon.style.top;
var id = setInterval(frame, 10);
function frame(){
if (Moon.style.top > 100) {
yposition--;
Moon.style.top = yposition + 'px';
} else {
clearInterval(id);
}
frame();
}
}
but for some reasons the image of moon stays at the bottom of the page and doesn't move at all. any ideas?
Try like this.
you need to calculate top offset of the div using moon.offsetTop
and a div does not have a onload event so you will have to call your Moon() function either from script or from body onload event
function Moon(){
var moon=document.getElementById("Moon");
var yposition= parseInt(moon.offsetTop) ;
var id = setInterval(frame, 10);
function frame()
{
if (moon.offsetTop > 10) {
yposition--;
document.getElementById("Moon").style.top = yposition + 'px';
} else {
clearInterval(id);
}
}
}
#Moon{
width: 300px;
height: 250px;
left: 50px;
top: 600px;
background: transparent url("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQh7mGmBMJ--wS711QkCEPHHS56jV15VmESttDbVLZPSI_FsMAyTQ") no-repeat ;
position: absolute;
}
<body onload="Moon()">
<div id="Moon"></div>
</body>

Check if a div touches another div

I've made margin of 2 divs move (using variable and variable++ or -- with style attribute in js to change margin) Like that:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset="utf-8" />
<title>Game</title>
<style>
body{
position: absolute;
background: #f00;
}
.point{
position: absolute;
width: 15px;
height: 15px;
background: #fff;
border-radius: 10px;
margin: 0px 0 0;
}
.player{
position: absolute;
text-align: center;
width: 200px;
height: 20px;
background: #0005ff;
margin: 550px 550px 0px;
}
</style>
<script>
var num = 550;
$(document).keydown(function (event) {
switch (event.keyCode) {
// Left Arrow
case 37: num = num-- - 15;
document.getElementById('player').style.margin = '550px ' + num + 'px 0px';
break;
// Right Arrow
case 39: num = 15 + num++;
document.getElementById('player').style.margin = '550px ' + num + 'px 0px';
break;
}
});
var nump = 0;
$(document).load(function () {
nump++;
document.getElementById('point').style.margin = nump + 'px 0px 0px';
});
</script>
</head>
<body>
<div class="point" id="point"></div>
<div class="player" id="player"></div>
</body>
</html>
Now I got problem about moving div named point.The div, point is not moving when I use $(document).load but the other div works. How can I fix that?
My second question is how can i check when div "point" touch div "player" then i'll return div point to the start and make a loop.
try this to move the point
var nump = 0;
var touch = false;
var flagtouch;
$(document).ready(function () {
flagtouch = setInterval(function(){
movePoint(nump);
},1000);
});
function movePoint()
{
document.getElementById('point').style.margin = nump + 'px 0px 0px';
touch = chekTouch(); // check whether the divs touches and return true if touched
if(touch)
{
clearInterval(flagtouch);
}
else
{
nump = nump+5;
}
}
For the second question:
With http://api.jquery.com/position/, you can known the position of both divs, and as you know too the width and height of the elements, you can calculate the region occupied by each element, and then when the elements touch each other.

Categories

Resources