How to fix Div element "jump" on drag? - javascript

The dragging works but the bug is that when I drag the element somehow "jumps" and does not flow with the mouse. See it in the code. Don't worry about removing event listeners, I will add them as soon as this works.
I have an issue on a draggable "div" element. I've searched many answers before I posted this question but nothing seems to be the solution(or maybe I am not understanding the problem really well).
Thank you!
const hotspot = document.getElementsByClassName("hotspot")[0];
const container = document.getElementsByClassName("container")[0];
let containerRect = container.getBoundingClientRect();
let hsRect = hotspot.getBoundingClientRect();
let relMouse = { x: 0, y: 0 };
let windowMouse = { x: 0, y: 0 };
let isUserIntercating = false;
const handlePointerUp = (e) => {
isUserIntercating = false;
};
const handlePointerDown = (e) => {
isUserIntercating = true;
hsRect = hotspot.getBoundingClientRect();
relMouse = { x: e.pageX - hsRect.x, y: e.pageY - hsRect.y };
window.addEventListener("pointerup", handlePointerUp, false);
};
const handlePointerMove = (e) => {
hsRect = hotspot.getBoundingClientRect();
containerRect = container.getBoundingClientRect();
windowMouse = { x: e.clientX - relMouse.x, y: e.clientY - relMouse.y };
};
const update = (t) => {
requestAnimationFrame(update);
if (isUserIntercating) {
hotspot.style.transform = `translate(${
windowMouse.x - containerRect.x
}px,0px)`;
}
};
update();
hotspot.addEventListener("pointerdown", handlePointerDown, false);
window.addEventListener("pointermove", handlePointerMove, false);
body {
font-family: sans-serif;
margin: 0;
}
.container {
padding: 0;
margin: 50px;
max-width: 600px;
min-height: 600px;
background-color: blanchedalmond;
}
.hotspot {
/* position: absolute; */
background-color: aqua;
/* transform: translate(100px, 100px); */
min-height: 100px;
max-width: 100px;
z-index: 200;
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div class="container">
<div class="hotspot"></div>
</div>
<script src="src/index.js"></script>
</body>
</html>

Try like this:
const hotspot = document.getElementsByClassName("hotspot")[0];
const container = document.getElementsByClassName("container")[0];
let containerRect = container.getBoundingClientRect();
let hsRect = hotspot.getBoundingClientRect();
let relMouse = { x: 0, y: 0 };
let windowMouse = { x: 0, y: 0 };
let isUserIntercating = false;
const handlePointerUp = (e) => {
isUserIntercating = false;
};
const handlePointerDown = (e) => {
isUserIntercating = true;
hsRect = hotspot.getBoundingClientRect();
relMouse = { x: e.pageX - hsRect.x, y: e.pageY - hsRect.y };
window.addEventListener("pointerup", handlePointerUp, false);
};
const handlePointerMove = (e) => {
hsRect = hotspot.getBoundingClientRect();
containerRect = container.getBoundingClientRect();
windowMouse = { x: e.clientX - relMouse.x, y: e.clientY - relMouse.y };
requestAnimationFrame(update);
};
const update = (t) => {
if (isUserIntercating) {
hotspot.style.transform = `translate(${
windowMouse.x - containerRect.x
}px,0px)`;
}
};
hotspot.addEventListener("pointerdown", handlePointerDown, false);
window.addEventListener("pointermove", handlePointerMove, false);
body {
font-family: sans-serif;
margin: 0;
}
.container {
padding: 0;
margin: 50px;
max-width: 600px;
min-height: 600px;
background-color: blanchedalmond;
}
.hotspot {
/* position: absolute; */
background-color: aqua;
/* transform: translate(100px, 100px); */
min-height: 100px;
max-width: 100px;
z-index: 200;
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div class="container">
<div class="hotspot"></div>
</div>
<script src="src/index.js"></script>
</body>
</html>
The issue seemed to be that the update function kept calling itself all the time, which is not really ideal. The update should only be called in the handlePointerMove function (only change the hotspot position when the mouse moves).

Related

How do I get the code in jsfiddle to work in my Visual Studio Code?

const canvasEle = document.getElementById('drawing-container');
const canvasPad = document.getElementById('pad');
const toolbar = document.getElementById('toolbar');
const context = canvasEle.getContext('2d');
const padContext = canvasPad.getContext('2d');
const canvasOffsetX = canvas.offsetLeft;
const canvasOffsetY = canvas.offsetTop;
canvas.width = window.innerWidth - canvasOffsetX;
canvas.height = window.innerHeight - canvasOffsetY;
let startPosition = {
x: 0,
y: 0
};
let lineCoordinates = {
x: 0,
y: 0
};
let isDrawStart = false;
const getClientOffset = (event) => {
const {
pageX,
pageY
} = event.touches ? event.touches[0] : event;
const x = pageX - canvasPad.offsetLeft;
const y = pageY - canvasPad.offsetTop;
return {
x,
y
}
}
toolbar.addEventListener('click', e => {
if (e.target.id === 'clear') {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
});
toolbar.addEventListener('change', e => {
if(e.target.id === 'stroke') {
ctx.strokeStyle = e.target.value;
}
if(e.target.id === 'lineWidth') {
lineWidth = e.target.value;
}
});
const drawLine = (ctx) => {
if (!isDrawStart) {
return;
}
ctx.beginPath();
ctx.moveTo(startPosition.x, startPosition.y);
ctx.lineTo(lineCoordinates.x, lineCoordinates.y);
ctx.stroke();
}
const mouseDownListener = (event) => {
startPosition = getClientOffset(event);
isDrawStart = true;
}
const mouseMoveListener = (event) => {
if (!isDrawStart) return;
lineCoordinates = getClientOffset(event);
clearCanvas(padContext);
drawLine(padContext);
}
const mouseupListener = (event) => {
clearCanvas(padContext);
drawLine(context);
isDrawStart = false;
}
const clearCanvas = (ctx) => {
ctx.clearRect(0, 0, canvasEle.width, canvasEle.height);
}
canvasPad.addEventListener('mousedown', mouseDownListener);
canvasPad.addEventListener('mousemove', mouseMoveListener);
canvasPad.addEventListener('mouseup', mouseupListener);
body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
color: white;
}
h1 {
background: #7F7FD5;
background: -webkit-linear-gradient(to right, #91EAE4, #86A8E7, #7F7FD5);
background: linear-gradient(to right, #91EAE4, #86A8E7, #7F7FD5);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.cnv-wrapper {
height: 100%;
display: flex;
}
.pad {
height: 100%;
display: flex;
border: 4px solid #333;
}
.container {
height: 100%;
display: flex;
}
#toolbar {
display: flex;
flex-direction: column;
padding: 5px;
width: 70px;
background-color: #202020;
}
#toolbar * {
margin-bottom: 6px;
}
#toolbar label {
font-size: 12px;
}
#toolbar input {
width: 100%;
}
#toolbar button {
background-color: #1565c0;
border: none;
border-radius: 4px;
color:white;
padding: 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device - width, initial - scale = 0.1">
<link rel = "stylesheet" href = "styles.css">
<title> Pipe Illustrator </title>
</head>
<body>
<section class = "container">
<div id = "toolbar">
<h1>Draw.</h1>
<label for="stroke">Stroke</label>
<input id="stroke" name='stroke' type="color">
<label for="lineWidth">Line Width</label>
<input id="lineWidth" name='lineWidth' type="number" value="5">
<button id="clear">Clear</button>
</div>
<div class = "drawing-container">
<canvas id = "drawing-container"></canvas>
</div>
<div class = "cnv-wrapper">
<canvas id = "cnv-wrapper"></canvas>
</div>
</section>
<script src = "./index.js"></script>
</body>
</html>
The project is to make a simple line drawer which makes allows me to draw fixed straight lines without the previous line being removed. The code written below is exactly what I need and was provided by another user from a question I asked previously about making it as my code wouldn't allow for the previous line to remain when drawing a new one.
This is the code below which is in jsfiddle, when I copy and paste it into my Visual studio code, I don't get the same output as I would in jsfiddle, the canvas doesn't appear nor does it allow anything to be drawn. Am I missing something ?
Right so this is the code i have written in VSC. It isn't entirely what was in the jsfiddle, i tried to integrate some other functions from another paint project i did. I was trying to add a toolbar for line colour and width. I think the way i have written it is contradicting it all got quite messy and was quite a fail. These are projects im doing to learn code as i am still a beginner to coding. Thank you for your help and input.
const canvasEle = document.querySelector('.draw-container');
const canvasPad = document.querySelector('.pad');
const context = canvasEle.getContext('2d');
const padContext = canvasPad.getContext('2d');
let startPosition = {
x: 0,
y: 0
};
let lineCoordinates = {
x: 0,
y: 0
};
let isDrawStart = false;
const getClientOffset = (event) => {
const {
pageX,
pageY
} = event.touches ? event.touches[0] : event;
const x = pageX - canvasPad.offsetLeft;
const y = pageY - canvasPad.offsetTop;
return {
x,
y
}
}
const drawLine = (ctx) => {
if (!isDrawStart) {
return;
}
ctx.beginPath();
ctx.moveTo(startPosition.x, startPosition.y);
ctx.lineTo(lineCoordinates.x, lineCoordinates.y);
ctx.stroke();
}
const mouseDownListener = (event) => {
startPosition = getClientOffset(event);
isDrawStart = true;
}
const mouseMoveListener = (event) => {
if (!isDrawStart) return;
lineCoordinates = getClientOffset(event);
clearCanvas(padContext);
drawLine(padContext);
}
const mouseupListener = (event) => {
clearCanvas(padContext);
drawLine(context);
isDrawStart = false;
}
const clearCanvas = (ctx) => {
ctx.clearRect(0, 0, canvasEle.width, canvasEle.height);
}
canvasPad.addEventListener('mousedown', mouseDownListener);
canvasPad.addEventListener('mousemove', mouseMoveListener);
canvasPad.addEventListener('mouseup', mouseupListener);
body {
background-color: #ccc;
}
.cnv-wrapper {
position: relative;
}
.pad {
position: absolute;
top: 0px;
left: 0px;
border: 1px solid #333;
}
.draw-container {
border: 1px solid #333;
}
<div class="cnv-wrapper">
<canvas class="draw-container" width="500" height="500"></canvas>
<canvas class="pad" width="500" height="500"></canvas>
</div>
From comments where I advise:
You can't just copy and paste code [from fiddle] without also using the appropriate html tags. Your CSS needs to go in style tags. Your scripts need to go in script tags. The dom elements, e.g. the "canvas" needs to go in the body tag. Etc. ... You may also need to affix the appropriate "doctype" and you may need to trigger the scripts to run on document load.
As an example, I tried the pasted code using the above advice on my own computer and it worked.
I'll show the complete source and then followup with a runnable version here on SO. Note that the runnable version uses SO's utility for such and as such you won't see all the various tags I mentioned, but the functionality remains the same just as with the "fiddle".
Corrected "pasted" source showing all the relevant tags you need to create:
<!doctype html> <!-- Add appropriate doctype -->
<html>
<head>
<style>
/* Paste the CSS in a style tag */
body {
background-color: #ccc;
}
.cnv-wrapper {
position: relative;
}
.pad {
position: absolute;
top: 0px;
left: 0px;
border: 1px solid #333;
}
.draw-container {
border: 1px solid #333;
}
</style>
</head>
<body>
<div class="cnv-wrapper">
<canvas class="draw-container" width="500" height="500"></canvas>
<canvas class="pad" width="500" height="500"></canvas>
</div>
<script>
// Paste your init scripts into the onload event to ensure they get ran after the canvas is created
window.onload = function() {
const canvasEle = document.querySelector('.draw-container');
const canvasPad = document.querySelector('.pad');
const context = canvasEle.getContext('2d');
const padContext = canvasPad.getContext('2d');
let startPosition = {
x: 0,
y: 0
};
let lineCoordinates = {
x: 0,
y: 0
};
let isDrawStart = false;
const getClientOffset = (event) => {
const {
pageX,
pageY
} = event.touches ? event.touches[0] : event;
const x = pageX - canvasPad.offsetLeft;
const y = pageY - canvasPad.offsetTop;
return {
x,
y
}
}
const drawLine = (ctx) => {
if (!isDrawStart) {
return;
}
ctx.beginPath();
ctx.moveTo(startPosition.x, startPosition.y);
ctx.lineTo(lineCoordinates.x, lineCoordinates.y);
ctx.stroke();
}
const mouseDownListener = (event) => {
startPosition = getClientOffset(event);
isDrawStart = true;
}
const mouseMoveListener = (event) => {
if (!isDrawStart) return;
lineCoordinates = getClientOffset(event);
clearCanvas(padContext);
drawLine(padContext);
}
const mouseupListener = (event) => {
clearCanvas(padContext);
drawLine(context);
isDrawStart = false;
}
const clearCanvas = (ctx) => {
ctx.clearRect(0, 0, canvasEle.width, canvasEle.height);
}
canvasPad.addEventListener('mousedown', mouseDownListener);
canvasPad.addEventListener('mousemove', mouseMoveListener);
canvasPad.addEventListener('mouseup', mouseupListener);
}
</script>
</body>
</html>
Now on to demonstrating this code works now here on SO.
Note that SO's intepreter of code also (like "fiddle") doesn't need the tags mentioned that would be needed when you copy and paste into your own editor. Therefore I re-mention where the pasted code goes in code comments.
// Your scripts will go in a <script> tag
// Use an onload event handler to ensure they get ran after the canvas is created
window.onload = function() {
const canvasEle = document.querySelector('.draw-container');
const canvasPad = document.querySelector('.pad');
const context = canvasEle.getContext('2d');
const padContext = canvasPad.getContext('2d');
let startPosition = {
x: 0,
y: 0
};
let lineCoordinates = {
x: 0,
y: 0
};
let isDrawStart = false;
const getClientOffset = (event) => {
const {
pageX,
pageY
} = event.touches ? event.touches[0] : event;
const x = pageX - canvasPad.offsetLeft;
const y = pageY - canvasPad.offsetTop;
return {
x,
y
}
}
const drawLine = (ctx) => {
if (!isDrawStart) {
return;
}
ctx.beginPath();
ctx.moveTo(startPosition.x, startPosition.y);
ctx.lineTo(lineCoordinates.x, lineCoordinates.y);
ctx.stroke();
}
const mouseDownListener = (event) => {
startPosition = getClientOffset(event);
isDrawStart = true;
}
const mouseMoveListener = (event) => {
if (!isDrawStart) return;
lineCoordinates = getClientOffset(event);
clearCanvas(padContext);
drawLine(padContext);
}
const mouseupListener = (event) => {
clearCanvas(padContext);
drawLine(context);
isDrawStart = false;
}
const clearCanvas = (ctx) => {
ctx.clearRect(0, 0, canvasEle.width, canvasEle.height);
}
canvasPad.addEventListener('mousedown', mouseDownListener);
canvasPad.addEventListener('mousemove', mouseMoveListener);
canvasPad.addEventListener('mouseup', mouseupListener);
}
/* Your CSS would go in a <style> tag */
body {
background-color: #ccc;
}
.cnv-wrapper {
position: relative;
}
.pad {
position: absolute;
top: 0px;
left: 0px;
border: 1px solid #333;
}
.draw-container {
border: 1px solid #333;
}
<!-- Your HTML would go in the <body> tag -->
<div class="cnv-wrapper">
<canvas class="draw-container" width="500" height="500"></canvas>
<canvas class="pad" width="500" height="500"></canvas>
</div>

How to draw via mouse-click without using the canvas-element

I am trying to create an "Etch-A-Sketch"-program, which should let the user draw only by clicking or holding the mouse-button. How can I realize that in JavaScript?
Somehow after the user chooses a color via clicking on the color-button, the color is already drawn as soon as the mouse cursor enters the drawing area (div class="container").
I've tried several functions, but it's still not working as expected...
Could someone please provide a hint?
"use strict";
const divContainer = document.querySelector(".container");
const btnsContainer = document.querySelector(".buttons");
const btnBlack = document.createElement("button");
const btnGreyScale = document.createElement("button");
const btnRgb = document.createElement("button");
const btnErase = document.createElement("button");
const btnShake = document.createElement("button");
function createGrid(col, rows) {
for(let i = 0; i < (col * rows); i++) {
const div = document.createElement("div");
divContainer.style.gridTemplateColumns = `repeat(${col}, 1fr)`;
divContainer.style.gridTemplateRows = `repeat(${rows}, 1fr)`;
divContainer.appendChild(div).classList.add("box");
}
}
createGrid(16,16)
let isDrawing = false;
window.addEventListener("mousedown", () => {
isDrawing = true;
});
window.addEventListener("mouseup", () => {
isDrawing = false;
});
function paintBlack() {
const boxes = divContainer.querySelectorAll(".box");
btnBlack.textContent = "Black";
btnBlack.addEventListener("click", function () {
boxes.forEach(box => box.addEventListener("mouseover", function () {
this.style.background = "#000";
}))
})
btnsContainer.appendChild(btnBlack).classList.add("btn");
}
paintBlack();
function paintGreyScale() {
const boxes = divContainer.querySelectorAll(".box");
btnGreyScale.textContent = "Grey";
btnGreyScale.addEventListener("click", function () {
boxes.forEach(box => box.addEventListener("mouseover", function () {
let randNum = Math.floor(Math.random() * 256);
let grayScale = `rgb(${randNum},${randNum},${randNum})`;
box.style.background = grayScale;
}))
})
btnsContainer.appendChild(btnGreyScale).classList.add("btn");
}
paintGreyScale();
function paintRgb() {
const boxes = divContainer.querySelectorAll(".box");
btnRgb.textContent = "Rainbow";
btnRgb.addEventListener("click", function () {
boxes.forEach(box => box.addEventListener("mouseover", function () {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
const rgb = `rgb(${r},${g},${b})`;
box.style.background = rgb;
}))
})
btnsContainer.appendChild(btnRgb).classList.add("btn");
}
paintRgb();
function erase() {
const boxes = divContainer.querySelectorAll(".box");
btnErase.textContent = "Erase";
btnErase.addEventListener("click", function () {
boxes.forEach(box => box.addEventListener("mouseover", function () {
this.style.background = "#FFF";
}))
})
btnsContainer.appendChild(btnErase).classList.add("btn");
}
erase();
function clearCanvas() {
const boxes = divContainer.querySelectorAll(".box");
btnShake.textContent = "Shake it!";
btnShake.addEventListener("click", function () {
boxes.forEach(box => box.style.backgroundColor = "#FFF");
})
btnsContainer.appendChild(btnShake).classList.add("shake");
}
clearCanvas();
btnShake.addEventListener("click", clearCanvas);
*,
*::before,
*::after {
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 16px;
}
body {
background: linear-gradient(to bottom, #1488CC, #2B32B2);
color: #FFF;
line-height: 1.5;
height: 100vh;
}
#wrapper {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
text-align: center;
}
.container {
width: 500px;
height: 500px;
display: grid;
background-color: #FFF;
box-shadow: 0 0 10px;
}
.box {
border: .5px solid #808080;
}
.shake {
animation: shake .5s linear 1;
}
#keyframes shake {
10%,
90% {
transform: translate3d(-1px, 0, 0);
}
20%,
80% {
transform: translate3d(2px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-4px, 0, 0);
}
40%,
60% {
transform: translate3d(4px, 0, 0);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Etch-A-Sketch</title>
</head>
<body>
<div id="wrapper">
<main>
<div class="container"></div>
<div class="buttons"></div>
</main>
</div>
<script src="etchAsketch.js"></script>
</body>
</html>
The mousedown event
window.addEventListener("mousedown", () => {
isDrawing = true;
});
sets isDrawing to true, and mouseup event to false, but you never use this variable to check whether the color should be drawn.
Solution: for each statement you have that's setting the background color of a square (except for clearCanvas), wrap it in an if statement checking if the user isDrawing:
if (isDrawing){this.style.background = "#000";} //black
if (isDrawing){this.style.background = grayScale;} //gray
if (isDrawing){this.style.background = rgb;} // rainbow
if (isDrawing){this.style.background = "#FFF";} // erase
boxes.forEach(box => box.style.backgroundColor = "#FFF");
}) //leave clearCanvas as it is

Moving the square using mousedown event on front end

Practicing some front end stuff just by using addEventListener. What I am trying to achieve here is that : click the square and then hold the mouse while moving the square to another place on the page and stop moving by release the mouse. Something is not right as the square seems to move in one direction only. Need some help here.
#square_cursor {
position: relative;
left: 109px;
top: 109px;
height: 50px;
width: 50px;
background-color: rgb(219, 136, 136);
border: 5px rgb(136, 219, 219) solid;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Drop</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id='square_cursor'></div>
<script>
let mouse_over_detector = false; //move the mouse over WITHOUT clicking
let mouse_click_detector = false; //clicking the mouse WITHOUT moveover
let drag_detector = false; //move and holding the mouse together
let window_click_detector = false;
let window_motion_detector = false;
let position_x = 0;
let position_y = 0;
let new_position_x = 0;
let new_position_y = 0;
window.addEventListener('mousedown', () => {
window_click_detector = true;
})
window.addEventListener('mouseup', () => {
window_click_detector = false;
brick.style.backgroundColor = 'rgb(219, 136, 136)';
})
let brick = document.getElementById('square_cursor');
//done
brick.addEventListener('mousedown', (event) => {
position_x = event.clientX;
position_y = event.clientY;
mouse_click_detector = true;
brick.style.backgroundColor = 'yellow';
})
brick.addEventListener('mousemove', (event) => {
if (mouse_click_detector === true) {
new_position_x = event.clientX;
new_position_y = event.clientY;
dragAndDrop(position_x, position_y, event.offsetX, event.offsetY);
}
});
brick.addEventListener('mouseout', () => {
mouse_over_detector = false;
mouse_click_detector = false;
})
brick.addEventListener('mouseup', () => {
mouse_click_detector = false;
})
function dragAndDrop(a, b, c, d) {
console.log('new x: ')
console.log(a - c);
console.log('new y: ')
console.log(b - d);
brick.style.left = a - c + 'px'
brick.style.top = b - d + 'px';
}
</script>
</body>
</html>
SOLVED IT THIS MORNING by using just addEventListener wooohoooo!
So the keys here are, first, being able to identify the DOM hierarchy and second, knowing what clientX does for the selected element. I am going to post my solution in snippet mode.
But I am still gonna give a vote to the 1st answer.
#square_cursor{
position:absolute;
left:109px;
top:109px;
height:50px;
width:50px;
background-color: rgb(219, 136, 136);
border:5px rgb(136, 219, 219) solid;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Drop</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id='square_cursor'></div>
<script>
let mouse_click_detector = false; //clicking the mouse WITHOUT moveover
let window_click_detector = false;
let position_x = 0;
let position_y = 0;
let click_position_x = 0;
let click_position_y = 0;
let brick = document.getElementById('square_cursor');
brick.addEventListener('mousedown', () => {
mouse_click_detector = true
})
window.addEventListener('mouseup', () => {
mouse_click_detector = false;
window_click_detector = false;
brick.style.backgroundColor = 'rgb(219, 136, 136)';
})
window.addEventListener('mousedown', (event) => {
if (mouse_click_detector === true) {
window_click_detector = true;
brick.style.backgroundColor = 'yellow';
click_position_x = event.offsetX;
click_position_y = event.offsetY;
}
})
window.addEventListener('mousemove', (event) => {
if (mouse_click_detector === true) {
position_x = event.clientX;
position_y = event.clientY;
brick.style.left = position_x - click_position_x + 'px';
brick.style.top = position_y - click_position_y + 'px';
}
})
</script>
</body>
</html>
"The most personal is the most creative" --- Martin Scorsese
Something like this..
//Make the DIV element draggable:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
#mydiv {
position: absolute; /* NECESSARY */
background-color: dodgerblue;
border: 1px solid #d3d3d3;
height: 20px;
width: 20px;
}
<div id="mydiv">
</div>
Minimalist code,
with simplified calculations by transform: translate(x,y).
const myDiv = document.querySelector('#my-div');
myDiv.ref_ms = { x: 0, y: 0 };
myDiv.addEventListener('mousedown', (e) =>
{
myDiv.ref_ms.x = e.clientX;
myDiv.ref_ms.y = e.clientY;
myDiv.classList.add('movCursor')
if (myDiv.style.transform !== '')
{
let [ mx, my ] = myDiv.style.transform.match(/-?\d*\.?\d+/g).map(Number);
myDiv.ref_ms.x -= mx;
myDiv.ref_ms.y -= my;
}
})
window.addEventListener('mousemove', e =>
{
if (myDiv.classList.contains('movCursor')
&& e.clientX > 0 && e.clientY > 0 )
{
myDiv.style = `transform: translate(${e.clientX - myDiv.ref_ms.x}px, ${e.clientY - myDiv.ref_ms.y}px);`;
}
})
window.addEventListener('mouseup', () =>
{
myDiv.classList.remove('movCursor')
})
#my-div {
background : dodgerblue;
border : 1px solid #d3d3d3;
height : 50px;
width : 50px;
margin : 30px;
cursor : grab;
}
.movCursor {
cursor : grabbing !important;
}
<div id="my-div"></div>

how can I reuse the functions of my code javascript?

I wanted to make an effect similar to "click and hold" of this page, but with some changes, with svg forms, the point is that I did two functions that do what I wanted to do very well, but at the moment I introduced another svg form, the Data of the effect is transferred to the other, affecting the execution of the functions, the question is, how do I prevent this from happening?
Note: The best way to see what is happening is to let one of the two complete.
Here is an example of what I have programmed
of course I leave you all the code that I have been working
//Efect Drivers
class EffectValues {
constructor(count, time, initOffset, label) {
this.count = count;
this.time = time;
this.initOffset = initOffset;
this.label = label;
}
}
//Controlers
let counter; //it will be interval controller
let globalCount = 0;
//Call objects DOM
const loader = document.querySelector('.loader');
const circle = document.querySelector('.circle');
const svgText = document.querySelector('.svgText');
const textSvg = document.querySelector('.textSvg');
//Preloader svg
const startCircle = new EffectValues(0, 3, 1300, circle);
const showEffect = new EffectValues(0, 3, 500, svgText);
//Mouse events
// Circle
loader.addEventListener('mousedown', e => {
increase(e, startCircle);
});
loader.addEventListener('mouseup', e => {
decrease(e, startCircle);
});
// Text SVG
textSvg.addEventListener('mousedown', e => {
increase(e, showEffect);
});
textSvg.addEventListener('mouseup', e => {
decrease(e, showEffect);
});
//main functions
const increase = (e, { count, initOffset, time, label }) => {
let flag = true;
// console.log(flag);
clearInterval(counter);
while (e.type == 'mousedown') {
counter = setInterval(() => {
if (globalCount < initOffset) {
count = initOffset - globalCount;
label.style.strokeDashoffset = count;
globalCount++;
}
}, time);
break;
}
return flag;
};
const decrease = (e, { count, initOffset, time, label }) => {
let flag = true;
// console.log(flag);
clearInterval(counter);
while (e.type == 'mouseup') {
counter = setInterval(() => {
if (globalCount >= 0 && globalCount < initOffset) {
count = -globalCount + initOffset;
label.style.strokeDashoffset = count;
globalCount--;
} else {
flag = false;
}
}, time);
break;
}
return flag;
};
:root {
--dark: #2f3640;
--dark-light: #353b48;
--blue: #192a56;
--blue-dark: #273c75;
--cian: #0097e6;
--cian-light: #00a8ff;
--orange: #c23616;
--orange-light: #e84118;
}
* {
margin: 0;
padding: 0;
}
body {
min-height: 100vh;
background-color: var(--dark);
display: flex;
justify-content: center;
align-content: center;
}
.loader {
position: relative;
width: 50%;
height: 100vh;
}
.loader svg {
position: absolute;
width: 550px;
height: 550px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.loader svg circle {
width: 100%;
height: 100%;
fill: none;
stroke-width: 10;
stroke: var(--cian);
stroke-linecap: round;
transform: translate(5px, 5px);
stroke-dasharray: 1300;
stroke-dashoffset: 1300;
}
.textSvg {
position: relative;
width: 40%;
}
.textSvg svg text {
stroke: var(--orange-light);
fill: none;
stroke-width: 3;
stroke-dasharray: 500;
stroke-dashoffset: 500;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<title>Loader</title>
</head>
<body>
<div class="loader">
<svg>
<circle class="circle" cx="200" cy="200" r="200"></circle>
</svg>
</div>
<div class="textSvg">
<svg
xmlns="http://www.w3.org/2000/svg"
width="1413"
height="274"
viewBox="0 0 1413 274"
>
<text
class="svgText"
transform="translate(0 198)"
fill="#c6e0ee"
font-size="100"
font-family="MonotypeCorsiva, Monotype Corsiva"
>
<tspan x="0" y="0">David Figueroa</tspan>
</text>
</svg>
</div>
</body>
<script src="main.js" defer></script>
</html>
I have been looking for information but nothing has helped me.
Beforehand thank you very much
You can implement your requirements by moving global variables and functions inside the class.
Codepen here
//Efect Drivers
class EffectValues {
constructor(time, initOffset, label) {
this.time = time;
this.initOffset = initOffset;
this.label = label;
this.counter;
this.globalCount = 0;
}
increase(e) {
let flag = true;
// console.log(flag);
clearInterval(this.counter);
while (e.type == 'mousedown') {
this.counter = setInterval(() => {
if (this.globalCount < this.initOffset) {
const count = this.initOffset - this.globalCount;
this.label.style.strokeDashoffset = count;
this.globalCount++;
}
}, this.time);
break;
}
return flag;
};
decrease(e) {
let flag = true;
// console.log(flag);
clearInterval(this.counter);
while (e.type == 'mouseup') {
this.counter = setInterval(() => {
if (this.globalCount >= 0 && this.globalCount < this.initOffset) {
const count = -this.globalCount + this.initOffset;
this.label.style.strokeDashoffset = count;
this.globalCount--;
} else {
flag = false;
}
}, this.time);
break;
}
return flag;
};
}
//Call objects DOM
const loader = document.querySelector('.loader');
const circle = document.querySelector('.circle');
const svgText = document.querySelector('.svgText');
const textSvg = document.querySelector('.textSvg');
//Preloader svg
const startCircle = new EffectValues(3, 1300, circle);
const letterEffect = new EffectValues(3, 500, svgText);
//Mouse events
// Circle
loader.addEventListener('mousedown', e => {
startCircle.increase(e);
});
loader.addEventListener('mouseup', e => {
startCircle.decrease(e);
});
// Text SVG
textSvg.addEventListener('mousedown', e => {
letterEffect.increase(e);
});
textSvg.addEventListener('mouseup', e => {
letterEffect.decrease(e);
});

Error in javascript Drag and Drop

I have done drag and drop of popup in JavaScript and it is dragged in all directions properly but down.MouseUp event is not triggered properly when I drag the popup towards down.So that it is moving even though I released mouse. I am really screwed up with this bug.Please help..I have to resolve it urgently....
Here is my code..
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<style>
body{
margin:0px;
padding:0px;
}
iframe{
width:800px;
height:500px;
}
img{border:none;}
.parentDisabled
{
width:100%;
height:100%
background-color:red;
position:absolute;
top:0;
left:0;
display:block;
border:1px solid blue;
}
#popup{
position:absolute;
width:800px;
height:500px;
border:2px solid #999188;
display:none;
}
#header{
padding-right:0px;
width:800px;
}
#close{
cursor:hand;
width:15px;
position: absolute;
right:0;
top:0;
padding:2px 2px 0px 0px;
}
#move{
cursor:move;
background:#999188;
width:800px;
line-height:10px;
}
#container{
}
.navigate{
border:1px solid black ;
background:#CC00FF;
color:white;
padding:5px;
cursor:hand;
font-weight:bold;
width:150px;
}
</style>
</HEAD>
<BODY>
<div onClick="showPopUp('w3schools');" class="navigate">W3Schools</div>
<div onClick="showPopUp('yahoo');" class="navigate">Yahoo</div>
<div onClick="showPopUp('linkedin');" class="navigate">LinkedIn</div>
<div onClick="showPopUp('vistex');" class="navigate">Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span>
<span id="close"><img src="close_red.gif" onClick="closePopUp()" alt="Close"/></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder=0>
page cannot be displayed
</iframe>
</div>
</div>
</BODY>
<script>
var popUpEle=null;
function showPopUp(value,evt)
{
evt = evt ? evt : window.event;
var left=evt.clientX;
var top=evt.clientY;
popUpEle = document.getElementById('popup');
if(popUpEle)
{
closePopUp();
var url= "http://www."+value+".com";
document.getElementById('Page_View').src=url;
popUpEle.style.left=left;
popUpEle.style.top=top;
popUpEle.style.filter="revealTrans( transition=1, duration=1)";
popUpEle.filters.revealTrans( transition=1, duration=1).Apply();
popUpEle.filters.revealTrans( transition=1, duration=1).Play();
popUpEle.style.display="inline";
}
}
function closePopUp(){
if(popUpEle)
{
popUpEle.style.filter="revealTrans( transition=0, duration=4)";
popUpEle.filters.revealTrans( transition=0, duration=5).Apply();
popUpEle.filters.revealTrans( transition=0, duration=5).Play();
popUpEle.style.display="none";
}
}
var dragApproved=false;
var DragHandler = {
// private property.
_oElem : null,
// public method. Attach drag handler to an element.
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin : function(e) {
var oElem = DragHandler._oElem = this;
if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
if (e.pageX || e.pageY)
{
oElem.mouseX = e.pageX;
oElem.mouseY = e.pageY;
}
else if (e.clientX || e.clientY) {
oElem.mouseX = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
oElem.mouseY = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
return false;
},
// private method. Drag (move) element.
_drag : function(e) {
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
var clientXTmp,clientYTmp;
if (e.pageX || e.pageY)
{
clientXTmp = e.pageX;
clientXTmp = e.pageY;
}
else if (e.clientX || e.clientY) {
clientXTmp = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
clientYTmp = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
var tmpX = x + (clientXTmp - oElem.mouseX);
var tmpY = y + (clientYTmp - oElem.mouseY);
if(tmpX<=0){tmpX = 0;}
if(tmpY<=0){tmpY = 0;}
oElem.style.left = tmpX + 'px';
oElem.style.top = tmpY + 'px';
oElem.mouseX = clientXTmp;
oElem.mouseY = clientYTmp;
return false;
},
// private method. Stop drag process.
_dragEnd : function()
{
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
}
}
DragHandler.attach(document.getElementById('popup'));</script>
</HTML>
First, your script didn't work in firefox or chrome so I did some changes.
Second, there's a limitation when moving the mouse very fast over the iframe. It seems that when the mouse is over an iframe, the 'mousemove' event isn't fired.
I inserted some fixes to your code and here it is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<style>
body
{
margin: 0px;
padding: 0px;
}
iframe
{
width: 800px;
height: 500px;
}
img
{
border: none;
}
.parentDisabled
{
width: 100%;
height: 100% background-color:red;
position: absolute;
top: 0;
left: 0;
display: block;
border: 1px solid blue;
}
#popup
{
position: absolute;
width: 800px;
height: 500px;
border: 2px solid #999188;
display: none;
}
#header
{
padding-right: 0px;
width: 800px;
height:20px;
background:#d8d8d8;
cursor:move;
}
#close
{
cursor: hand;
width: 15px;
position: absolute;
right: 0;
top: 0;
padding: 2px 2px 0px 0px;
}
#move
{
cursor: move;
background: #999188;
width: 800px;
line-height: 10px;
}
#container
{
}
.navigate
{
border: 1px solid black;
background: #CC00FF;
color: white;
padding: 5px;
cursor: hand;
font-weight: bold;
width: 150px;
}
</style>
</head>
<body>
<div onclick="showPopUp('w3schools', event);" class="navigate">
W3Schools</div>
<div onclick="showPopUp('yahoo', event);" class="navigate">
Yahoo</div>
<div onclick="showPopUp('linkedin', event);" class="navigate">
LinkedIn</div>
<div onclick="showPopUp('vistex', event);" class="navigate">
Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span><span id="close">
<img src="close_red.gif" onclick="closePopUp()" alt="Close" /></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder="0">page cannot be displayed </iframe>
</div>
</div>
<div id='log'></div>
<script type="text/javascript">
var popUpEle = null;
var isIE = navigator.appVersion.indexOf("MSIE") !== -1;
function showPopUp(value, evt)
{
evt = evt ? evt : window.event;
var left = evt.clientX;
var top = evt.clientY;
popUpEle = document.getElementById('popup');
if (popUpEle)
{
closePopUp();
var url = "http://www." + value + ".com";
document.getElementById('Page_View').src = url;
popUpEle.style.left = left;
popUpEle.style.top = top;
popUpEle.style.filter = "revealTrans( transition=1, duration=1)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 1, duration = 1).Apply();
popUpEle.filters.revealTrans(transition = 1, duration = 1).Play();
}
popUpEle.style.display = "block";
}
}
function closePopUp()
{
if (popUpEle)
{
popUpEle.style.filter = "revealTrans( transition=0, duration=4)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 0, duration = 5).Apply();
popUpEle.filters.revealTrans(transition = 0, duration = 5).Play();
}
popUpEle.style.display = "none";
}
}
var DragHandler = {
// private property.
_oElem: null,
_dragElement: null,
// public method. Attach drag handler to an element.
attach: function (oElem)
{
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin: function (e)
{
e = window.event || e;
var oElem = DragHandler._oElem = this;
// saving current mouse position
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
// if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
// if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
// var x = parseInt(oElem.style.left);
// var y = parseInt(oElem.style.top);
// e = e ? e : window.event;
// if (e.pageX || e.pageY)
// {
// oElem.mouseX = e.pageX;
// oElem.mouseY = e.pageY;
// }
// else if (e.clientX || e.clientY)
// {
// oElem.mouseX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
// oElem.mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
// }
// saving the element which invoked the drag
// to capture 'mouseout' event
DragHandler._dragElement = document.elementFromPoint(e.clientX, e.clientY);
DragHandler._dragElement.onmouseout = DragHandler._dragMouseOut;
document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
return false;
},
_dragMouseOut: function (e)
{
e = window.event || e;
//document.getElementById("log").innerHTML += "mouseout!: " + e.clientX + "," + e.clientY + "<br/>";
// calculating move by
var oElem = DragHandler._oElem;
var moveByX = e.clientX - oElem.mouseX;
var moveByY = e.clientY - oElem.mouseY;
//if (document.getElementById("log").offsetHeight > 100)
//document.getElementById("log").innerHTML = "";
document.getElementById("log").innerHTML += "mouseout x: " + moveByX + ", y:" + moveByY + "<br/>";
// setting position
var futureX = (x + moveByX);
if (futureX < 0) futureX = 0;
var futureY = (y + moveByY);
if (futureY < 0) futureY = 0;
oElem.style.left = futureX + 'px';
oElem.style.top = futureY + 'px';
oElem.mouseX = e.clientX;
if (oElem.mouseX < 0) oElem.mouseX = 0;
oElem.mouseY = e.clientY;
if (oElem.mouseY < 0) oElem.mouseY = 0;
},
// private method. Drag (move) element.
_drag: function (e)
{
e = window.event || e;
var oElem = DragHandler._oElem;
document.getElementById("log").innerHTML += "mousemove!!!<br/>";
// current element position
var x = oElem.offsetLeft;
var y = oElem.offsetTop;
// calculating move by
var moveByX = e.clientX - oElem.mouseX;
var moveByY = e.clientY - oElem.mouseY;
//if (document.getElementById("log").offsetHeight > 100)
//document.getElementById("log").innerHTML = "";
document.getElementById("log").innerHTML += "mouse move x: " + moveByX + ", y:" + moveByY + "<br/>";
// setting position
var futureX = (x + moveByX);
if (futureX < 0) futureX = 0;
var futureY = (y + moveByY);
if (futureY < 0) futureY = 0;
oElem.style.left = futureX + 'px';
oElem.style.top = futureY + 'px';
oElem.mouseX = e.clientX;
if (oElem.mouseX < 0) oElem.mouseX = 0;
oElem.mouseY = e.clientY;
if (oElem.mouseY < 0) oElem.mouseY = 0;
// canceling selection
if (!isIE)
return false;
else
document.selection.empty();
},
// private method. Stop drag process.
_dragEnd: function ()
{
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
DragHandler._dragElement.onmouseout = null;
DragHandler._dragElement = null;
}
}
DragHandler.attach(document.getElementById('popup'));
</script>
</body></html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<style>
body
{
margin: 0px;
padding: 0px;
}
iframe
{
width: 400px;
height: 200px;
}
img
{
border: none;
}
.parentDisabled
{
width: 100%;
height: 100% background-color:red;
position: absolute;
top: 0;
left: 0;
display: block;
border: 1px solid blue;
}
#popup
{
position: absolute;
width: 400px;
height: 200px;
border: 2px solid #999188;
display: none;
}
#header
{
padding-right: 0px;
width: 400px;
height:20px;
background:#d8d8d8;
cursor:move;
}
#close
{
cursor: hand;
width: 15px;
position: absolute;
right: 0;
top: 0;
padding: 2px 2px 0px 0px;
}
#move
{
cursor: move;
background: #999188;
width: 400px;
line-height: 10px;
}
#container
{
}
.navigate
{
border: 1px solid black;
background: #CC00FF;
color: white;
padding: 5px;
cursor: hand;
font-weight: bold;
width: 150px;
}
</style>
</head>
<body>
<div onclick="showPopUp('w3schools', event);" class="navigate">
W3Schools</div>
<div onclick="showPopUp('yahoo', event);" class="navigate">
Yahoo</div>
<div onclick="showPopUp('linkedin', event);" class="navigate">
LinkedIn</div>
<div onclick="showPopUp('vistex', event);" class="navigate">
Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span><span id="close">
<img src="close_red.gif" onclick="closePopUp()" alt="Close" /></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder="0">page cannot be displayed </iframe>
</div>
</div>
<div id='log'></div>
</body>
<script>
var popUpEle = null;
var isIE = navigator.appVersion.indexOf("MSIE") !== -1;
function showPopUp(value, evt)
{
evt = evt ? evt : window.event;
var left = evt.clientX;
var top = evt.clientY;
popUpEle = document.getElementById('popup');
if (popUpEle)
{
closePopUp();
var url = "http://www." + value + ".com";
document.getElementById('Page_View').src = url;
popUpEle.style.left = left;
popUpEle.style.top = top;
popUpEle.style.filter = "revealTrans( transition=1, duration=1)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 1, duration = 1).Apply();
popUpEle.filters.revealTrans(transition = 1, duration = 1).Play();
}
popUpEle.style.display = "block";
}
}
function closePopUp()
{
if (popUpEle)
{
popUpEle.style.filter = "revealTrans( transition=0, duration=4)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 0, duration = 5).Apply();
popUpEle.filters.revealTrans(transition = 0, duration = 5).Play();
}
popUpEle.style.display = "none";
}
}
var dragApproved=false;
var DragHandler = {
// private property.
_oElem : null,
// public method. Attach drag handler to an element.
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin : function(e) {
if (!document.all)return;
var oElem = DragHandler._oElem = this;
if (isNaN(parseInt(oElem.style.left))){ oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
if (e.pageX || e.pageY)
{
oElem.mouseX = e.pageX;
oElem.mouseY = e.pageY;
}
else if (e.clientX || e.clientY) {
oElem.mouseX = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
oElem.mouseY = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
document.onmousemove = DragHandler._drag;
dragApproved=true;
document.onmouseup = DragHandler._dragEnd;
return false;
},
// private method. Drag (move) element.
_drag : function(e) {
if(dragApproved && event.button==1)
{
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
var clientXTmp,clientYTmp;
if (e.pageX || e.pageY)
{
clientXTmp = e.pageX;
clientXTmp = e.pageY;
}
else if (e.clientX || e.clientY) {
clientXTmp = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
clientYTmp = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
var tmpX = x + (clientXTmp - oElem.mouseX);
var tmpY = y + (clientYTmp - oElem.mouseY);
if(tmpX<=0){tmpX = 0;}
if(tmpY<=0){tmpY = 0;}
//Avoiding scrolling of rigth and bottom of the window
if((tmpX+oElem.offsetWidth) > document.body.offsetWidth)
{
tmpX= document.body.offsetWidth-oElem.offsetWidth;
}
if((tmpY+oElem.offsetHeight) > document.body.offsetHeight)
{
tmpY= document.body.offsetHeight-oElem.offsetHeight;
}
oElem.style.left = tmpX + 'px';
oElem.style.top = tmpY + 'px';
oElem.mouseX = clientXTmp;
oElem.mouseY = clientYTmp;
return false;
}
},
// private method. Stop drag process.
_dragEnd : function()
{
dragApproved=false;
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
}
}
DragHandler.attach(document.getElementById('popup'));
</script>
</HTML>

Categories