how to drag and drop a <div> across the page - javascript

I am developing an web application where I am trying simulate a popup window using tags , for style purpose. I done this with this javascript code:
<script>
function handleClick(url){
document.getElementById("results").style.display = 'block';
document.getElementById("about").innerHTML='<object type="text/html" data="'+url+'" ></object>';
}
function cleanDiv() {
document.getElementById("results").style.display = 'none';
document.getElementById("about").innerHTML=' ';
}
</script>
associated to this html code:
<section class="about" id="results">
<div align="right">Fechar</div>
<div id="about" algin="center"></div>
</section>
and the style is on my css file.
I have almost all what I want, but I wish this "popup window" don't stay fixed in a unique position on the page, and the user could move it around with the mouse.
Someone knows how to make this with javascript/html/css only?

You are looking for the HTML5 draggable attribute and events. Make the element draggable by setting draggable="true" and ondragstart="dragElem(event)". Then write your code in function dragElem(ev) { }. See W3Schools

After more search, I ended with this code, from site http://waseemblog.com/42/movable-div-using-javascript.html
html:
<section class="about" id="results" style="left: 183px; top: 111px;" onMouseDown="dragStart(event, 'results');">
<div align="right">X</div>
<div id="content" align="center"></div>
</section>
javascript:
function getID(id)
{
return document.getElementById(id);
}
// Global object to hold drag information.
var dragObj = new Object();
function dragStart(event, id) {
var x, y;
dragObj.elNode = getID(id);
// Get cursor position with respect to the page.
try {
x = window.event.clientX + document.documentElement.scrollLeft
+ document.body.scrollLeft;
y = window.event.clientY + document.documentElement.scrollTop
+ document.body.scrollTop;
}
catch (e) {
x = event.clientX + window.scrollX;
y = event.clientY + window.scrollY;
}
// Save starting positions of cursor and element.
dragObj.cursorStartX = x;
dragObj.cursorStartY = y;
dragObj.elStartLeft = parseInt(dragObj.elNode.style.left, 10);
dragObj.elStartTop = parseInt(dragObj.elNode.style.top, 10);
if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
if (isNaN(dragObj.elStartTop)) dragObj.elStartTop = 0;
// Capture mousemove and mouseup events on the page.
try {
document.attachEvent("onmousemove", dragGo);
document.attachEvent("onmouseup", dragStop);
window.event.cancelBubble = true;
window.event.returnValue = false;
}
catch (e) {
document.addEventListener("mousemove", dragGo, true);
document.addEventListener("mouseup", dragStop, true);
event.preventDefault();
}
}
function dragGo(event) {
var x, y;
// Get cursor position with respect to the page.
try {
x = window.event.clientX + document.documentElement.scrollLeft
+ document.body.scrollLeft;
y = window.event.clientY + document.documentElement.scrollTop
+ document.body.scrollTop;
}
catch (e) {
x = event.clientX + window.scrollX;
y = event.clientY + window.scrollY;
}
// Move drag element by the same amount the cursor has moved.
var drLeft = (dragObj.elStartLeft + x - dragObj.cursorStartX);
var drTop = (dragObj.elStartTop + y - dragObj.cursorStartY);
if (drLeft > 0)
{
dragObj.elNode.style.left = drLeft + "px";
}
else
{
dragObj.elNode.style.left = "1px";
}
if (drTop > 0)
{
dragObj.elNode.style.top = drTop + "px";
}
else
{
dragObj.elNode.style.top = "1px";
}
try {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
catch(e){
event.preventDefault();
}
}
function dragStop(event) {
// Stop capturing mousemove and mouseup events.
try {
document.detachEvent("onmousemove", dragGo);
document.detachEvent("onmouseup", dragStop);
}
catch (e) {
document.removeEventListener("mousemove", dragGo, true);
document.removeEventListener("mouseup", dragStop, true);
}
}
It can be bigger than your counterpart using jquery, but I guess it works fine in most browsers available today.

Related

drag and drop soccer score incrementor Javascript

I haven't been able to correctly build logic. After dropping soccer ball into the goal, the score does not increment. As stated in my JS script code, I attempted to add score++ to scoreDisplay function (in bold).
Thank you for looking at this issue.
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Score:<span id="score">0</span></h3>
<button id="start-button">Start/Pause</button>
<p>Drag the ball.</p>
<img src="https://en.js.cx/clipart/soccer-gate.svg" id="gate" class="droppable">
<img src="https://picsum.photos/150/150" id="ball">
<script>
const scoreDisplay = document.querySelector('#score')
let score = 0
let currentDroppable = null;
ball.onmousedown = function(event) {
let shiftX = event.clientX - ball.getBoundingClientRect().left;
let shiftY = event.clientY - ball.getBoundingClientRect().top;
ball.style.position = 'absolute';
ball.style.zIndex = 1000;
document.body.append(ball);
moveAt(event.pageX, event.pageY);
function moveAt(pageX, pageY) {
ball.style.left = pageX - shiftX + 'px';
ball.style.top = pageY - shiftY + 'px';
}
function onMouseMove(event) {
moveAt(event.pageX, event.pageY);
ball.hidden = true;
let elemBelow = document.elementFromPoint(event.clientX, event.clientY);
ball.hidden = false;
if (!elemBelow) return;
let droppableBelow = elemBelow.closest('.droppable');
if (currentDroppable != droppableBelow) {
if (currentDroppable) { // null when we were not over a droppable before this event
leaveDroppable(currentDroppable);
}
currentDroppable = droppableBelow;
if (currentDroppable) { // null if we're not coming over a droppable now
// (maybe just left the droppable)
enterDroppable(currentDroppable);
}
//add score
**function scoreIncrement() {
score++;
document.getElementById("score").innerText="Score: " + score;**
}​
}
}
document.addEventListener('mousemove', onMouseMove);
ball.onmouseup = function() {
document.removeEventListener('mousemove', onMouseMove);
ball.onmouseup = null;
};
};
function enterDroppable(elem) {
elem.style.background = 'pink';
}
function leaveDroppable(elem) {
elem.style.background = '';
}
ball.ondragstart = function() {
return false;
};
</script>
</body>
</html>
Thanks again for for taking the time to look this over
you were almost there!. You were missing what is called a "flag". That is a variable (usually true/false) that holds some information that allows you to make decisions in the right event (which you had).
In this case a flag could tell me if I am over or not the goal, so that when I drop the ball I can add a point to the score.
As you can see in the code below, when you enterDroppable the flag is set to true and when you leaveDroppable its set back to false; then when the event mouseUp is triggered, the flag is checked. If the flag was true, then the score is incremented (and its value is updated on the screen)
Note that I changed the style of the ball so it looks more like a ball. Also note that its not a good practice to subscribe and remove events inside other events. Its better to have the events subscribed once and have more flags: for example, set a flag in the mouseDown to know that the ball was "grabed", then the mouseMove event would check that flag to see if it had to move the ball or not. I leave it as is, so not to change your code much but keep it in mind.
See the working code below (scroll all the way down and click on "Run the snipped code" to see it in action). Also if this solved your question dont forget to mark it as such using the green check left to the answer.
const scoreDisplay = document.querySelector('#score')
let score = 0
let currentDroppable = null;
let ballIsOverDroppable = false;
ball.onmousedown = function(event) {
let shiftX = event.clientX - ball.getBoundingClientRect().left;
let shiftY = event.clientY - ball.getBoundingClientRect().top;
ball.style.position = 'absolute';
ball.style.zIndex = 1000;
document.body.append(ball);
moveAt(event.pageX, event.pageY);
function moveAt(pageX, pageY) {
ball.style.left = pageX - shiftX + 'px';
ball.style.top = pageY - shiftY + 'px';
}
function onMouseMove(event) {
moveAt(event.pageX, event.pageY);
ball.hidden = true;
let elemBelow = document.elementFromPoint(event.clientX, event.clientY);
ball.hidden = false;
if (!elemBelow) return;
let droppableBelow = elemBelow.closest('.droppable');
if (currentDroppable != droppableBelow) {
if (currentDroppable) { // null when we were not over a droppable before this event
leaveDroppable(currentDroppable);
}
currentDroppable = droppableBelow;
if (currentDroppable) { // null if we're not coming over a droppable now
// (maybe just left the droppable)
enterDroppable(currentDroppable);
}
}
}
document.addEventListener('mousemove', onMouseMove);
ball.onmouseup = function() {
document.removeEventListener('mousemove', onMouseMove);
ball.onmouseup = null;
if (ballIsOverDroppable) {
score++;
scoreDisplay.textContent = `${score}`;
}
};
};
function enterDroppable(elem) {
elem.style.background = 'pink';
ballIsOverDroppable = true;
}
function leaveDroppable(elem) {
elem.style.background = '';
ballIsOverDroppable = false;
}
ball.ondragstart = function() {
return false;
};
<h3>Score:<span id="score">0</span></h3>
<button id="start-button">Start/Pause</button>
<p>Drag the ball.</p>
<img src="https://en.js.cx/clipart/soccer-gate.svg" id="gate" class="droppable">
<img src="https://picsum.photos/20/20" id="ball" style="border-radius: 20px; border: 2px solid black;">

Overlay an iframe on another iframe

I have a javascript code, using which an iframe moves with mouse pointer.
and when I slide mouse over another iframe (e.x youtube embed video), the iframe doesn't move with mouse while mouse pointer is on youtube video.
what can be done? thanks
<script type="text/javascript">
var opacity = 1;
var time = 3500000;
if (document.cookie.indexOf('visited=true') == -1) {
(function openColorBox() {
if ((document.getElementById) && window.addEventListener || window.attachEvent) {
var hairCol = "#ff0000";
var d = document;
var my = -10;
var mx = -10;
var r;
var vert = "";
var idx = document.getElementsByTagName('div').length;
var thehairs = "<iframe id='theiframe' scrolling='no' frameBorder='0' allowTransparency='true' src='b.html' style='margin: px 0px 0px px; position:fixed;width:200px;height:200px;overflow:hidden;border:0;opacity:" + opacity + ";filter:alpha(opacity=" + opacity * 100 + ");'></iframe>";
document.write(thehairs);
var like = document.getElementById("theiframe");
document.getElementsByTagName('body')[0].appendChild(like);
var pix = "px";
var domWw = (typeof window.innerWidth == "number");
var domSy = (typeof window.pageYOffset == "number");
if (domWw) r = window;
else {
if (d.documentElement && typeof d.documentElement.clientWidth == "number" && d.documentElement.clientWidth != 0) r = d.documentElement;
else {
if (d.body && typeof d.body.clientWidth == "number") r = d.body
}
}
if (time != 0) {
setTimeout(function() {
document.getElementsByTagName('body')[0].removeChild(like);
if (window.addEventListener) {
document.removeEventListener("mousemove", mouse, false)
} else if (window.attachEvent) {
document.detachEvent("onmousemove", mouse)
}
}, time)
}
function scrl(yx) {
var y, x;
if (domSy) {
y = r.pageYOffset;
x = r.pageXOffset
} else {
y = r.scrollTop;
x = r.scrollLeft
}
return (yx == 0) ? y : x
}
function mouse(e) {
var msy = (domSy) ? window.pageYOffset : 0;
if (!e) e = window.event;
if (typeof e.pageY == 'number') {
my = e.pageY - 0 - msy;
mx = e.pageX - 0
} else {
my = e.clientY - 6 - msy;
mx = e.clientX - 6
}
vert.top = my + scrl(0) + pix;
vert.left = mx + pix
}
function ani() {
vert.top = my + scrl(0) + pix;
setTimeout(ani, 300)
}
function init() {
vert = document.getElementById("theiframe").style;
ani()
}
if (window.addEventListener) {
window.addEventListener("load", init, false);
document.addEventListener("mousemove", mouse, false)
} else if (window.attachEvent) {
window.attachEvent("onload", init);
document.attachEvent("onmousemove", mouse)
}
}
})();
var oneDay = 1000 * 60 * 30;
var expires = new Date((new Date()).valueOf() + oneDay);
document.cookie = "visited=true;expires=" + expires.toUTCString()
}
</script>
<iframe width="420" height="315" src="https://www.youtube.com/embed/sTesehdHbqs" style="display:block; position:static;"frameborder="0" allowfullscreen></iframe>
Without seeing your HTML, the best guess is: you're not going to be able to do this. The issue is that, once you move your mouse into an iframe that has an origin different from your page, mouse events will not fire out to your script, and therefore you won't be able to update the position of your iframe. DEMO: Note how the mouse coordinates stop updating once you move your mouse pointer inside the iframe.
function mouseMoveListener() {
var outputX = document.querySelector('#mouseX');
var outputY = document.querySelector('#mouseY');
return function(ev) {
outputX.innerText = ev.clientX;
outputY.innerText = ev.clientY;
};
}
function test(ev) {console.log('ev::', ev.clientX);}
document.addEventListener('mousemove', mouseMoveListener());
<div>Mouse position:
<span id="mouseX"></span>
,
<span id="mouseY"></span>
</div>
<iframe src="http://www.example.com" width="200" height="200"></iframe>
If you don't need to let your users interact with the content of the iframe, you can cheat this by overlaying a transparent div on top of the iframe. That prevents mouse events from "falling through" to the iframe beneath them, while still showing the content of the iframe. DEMO: But note that the iframe doesn't allow you to scroll, since mouse events (like clicks on the scroll bar or wheel events) are captured by the overlay div.
function mouseMoveListener() {
var outputX = document.querySelector('#mouseX');
var outputY = document.querySelector('#mouseY');
return function(ev) {
outputX.innerText = ev.clientX;
outputY.innerText = ev.clientY;
};
}
function test(ev) {console.log('ev::', ev.clientX);}
document.addEventListener('mousemove', mouseMoveListener());
#iframe-wrapper {
position: relative;
}
#iframe-wrapper iframe {
position: relative;
z-index: 0;
}
#iframe-wrapper .overlay {
position: absolute;
background: transparent;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 2;
}
<div>Mouse position:
<span id="mouseX"></span>
,
<span id="mouseY"></span>
</div>
<div id="iframe-wrapper">
<iframe src="http://www.example.com" width="200" height="200"></iframe>
<div class="overlay"></div>
</div>
However, if you're displaying a YouTube video, it's unlikely this will satisfy your requirements, since user interaction is a key part of the viewing experience.

Javascript drag and drop code works on div but doesn't work on img

I'm fairly new to JavaScript, so any help would be awesome!
I created this small block of code that let's me grab a div and drag it around. I assign the "dragme" id to the div and all is fine and dandy. The problem is that if I replace that div from my html and put an img element instead (obviously assigning the "dragme" id to the img), things don't work as expected.
When I click to drag the img, it actually moves for about 3 or 4 pixels then it freezes until I lift the mouse button (mouseup).
Is there some property or characteristic that would prevent the img element from acting the same way as the div does?
var isClicked = false;
var startClientX = 0;
var startClientY = 0;
var startLeft = 0;
var startTop = 0;
window.addEventListener("load", addListeners, true);
function addListeners()
{
document.getElementById("dragme").addEventListener("mousedown", mouseIsDown, false);
document.getElementById("dragme").addEventListener("mouseup", mouseIsUp, false);
window.addEventListener("mousemove", moveImage, false);
function mouseIsDown(e)
{
if (isClicked == false)
{
isClicked = true;
startClientX = e.clientX;
startClientY = e.clientY;
startLeft = document.getElementById("dragme").offsetLeft;
startTop = document.getElementById("dragme").offsetTop;
}
}
function mouseIsUp()
{
if (isClicked == true)
{
isClicked = false;
}
}
function moveImage(e)
{
if (isClicked == true)
{
imageLeftDif = e.clientX - startClientX;
imageTopDif = e.clientY - startClientY;
var newLeftPos = (startLeft + imageLeftDif) + "px";
var newTopPos = (startTop + imageTopDif) + "px";
document.getElementById("dragme").style.left = newLeftPos;
document.getElementById("dragme").style.top = newTopPos;
}
}
}
This fixed the problem (answer provided as a comment by syazdani):
I'd venture to say that the built in browser drag and drop for images
is kicking in. Try e.preventDefault and return false in the mousedown
handler. – syazdani Dec 2 '12 at 17:26

Make img not to move in html

I have an image on my page, and I would like to listen to onmousemove events when the mouse is down. But I can't because in my browser (Firefox), when I drag an image, well actually I drag the image, which I don't want.
Here's my code:
JavaScript part:
document.onmousemove=getMouseCoordinates;
var x;
var y;
var clicked = false;
function getMouseCoordinates(event){
ev = event || window.event;
x = ev.pageX;
y = ev.pageY;
}
function onClickMap(){
var obj = document.getElementById("selectArea");
var tempX = x;
var tempY = y;
obj.style.left = tempX + "px";
obj.style.top = tempY + "px";
clicked = true;
}
function onMoveMap(){
if(clicked){
var obj = document.getElementById("selectArea");
var xToSize = Math.abs(parseInt(obj.style.left) - x);
var yToSize = Math.abs(parseInt(obj.style.top) - y);
obj.style.width = xToSize + "px";
obj.style.height = yToSize + "px";
}
}
HTML part:
<img src="pixels.png" id ="pixelDiv" usemap="#pixelMap" onClick="onClickMap()" onmousemove="onMoveMap()">
Here is a jQuery solution.
This will disable all drags:
$(document).bind("dragstart", function() {
return false;
});
If you want to disable drags only on img elements:
$(document).bind("dragstart", function(e) {
if (e.target.nodeName.toUpperCase() == "IMG") {
return false;
}
});
You can add a mousedown handler that just returns false. This seems to stop the dragging in FF.
ok it's nice, but I suppose it is something firefox specific, now I disabled the onlcick and onmove methods of my image, but I can stil drag the image
now I've found the solution, I was looking for this
http://www.develobert.info/2008/10/disable-firefox-image-drag.html

Drag and drop JavaScript query

<script type="text/javascript">
//mouse down on dragged DIV element
var flag = 0;
function startdrag(t, e) {
if (e.preventDefault) e.preventDefault(); //line for IE compatibility
e.cancelBubble = true;
t.style.position = "absolute";
window.document.onmousemove = dodrag;
document.getElementById("resulttable").onmouseup = end;
window.document.onmouseup = stopdrag;
window.document.s = t;
return false;
}
//move the DIV
function dodrag(e) {
//alert("dodrag");
if (!e) e = event; //line for IE compatibility
t = window.document.s;
if (t != null) {
t.style.left = (t.offsetLeft + e.clientX - t.dragX) + "px";
posleft = (t.offsetLeft + e.clientX - t.dragX) + "px";
t.style.top = (t.offsetTop + e.clientY - t.dragY) + "px";
t.dragX = e.clientX;
t.dragY = e.clientY;
}
return false;
}
//restore event-handlers
function stopdrag(e) {
if (flag == 1)
window.document.s = null;
else
alert("outside valid range"); // code for setting object to original area
return false;
}
function end(e) {
flag = 1;
return false;
}
</script>
// table from where we start dragging
<td id="<%= i %>"><div onmousedown="startdrag(this, event);"> <%Response.Write(row1[i].ToString()); %></div> </td>
// target div where to put element
<div id="resulttable" onmouseup="end(event);" >Put whatever you want in here<br />
<br />
<br />
<br />
</div>
PROBLEM:
When I start dragging, all statements of startdrag() are called and then dodrag() and so on.
end() is not called even though we put element on target div, so flag remains as 0.
As per my comment, if you can use Jquery UI and Jquery as it will do all the heavy lifting.
With regards to your question try end() stopdrag(), javascript can work very differently across browsers, check in another browser to see if the call actually works... console.debug("method called"); is a good command to add to your code to help with debugging...

Categories

Resources