Javascript: Dragable Element Messed up When There is <select> in Element - javascript

I am implementing the code that I get from internet and I put a select on it.
The element is messed up when I do this step on Chrome browser;
I move the element and drag it.
I choose select and then the element is moving to left top page.
Please help, just simply copy and paste this code to your editor and run it;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<script type="text/javascript">
//object of the element to be moved
_item = null;
//stores x & y co-ordinates of the mouse pointer
mouse_x = 0;
mouse_y = 0;
// stores top,left values (edge) of the element
ele_x = 0;
ele_y = 0;
//bind the functions
function move_init()
{
document.onmousemove = _move;
document.onmouseup = _stop;
}
//destroy the object when we are done
function _stop()
{
_item = null;
}
//main functions which is responsible for moving the element (div in our example)
function _move(e)
{
mouse_x = document.all ? window.event.clientX : e.pageX;
mouse_y = document.all ? window.event.clientY : e.pageY;
if(_item != null)
{
_item.style.left = (mouse_x - ele_x) + "px";
_item.style.top = (mouse_y - ele_y) + "px";
}
}
//will be called when use starts dragging an element
function _move_item(ele)
{
//store the object of the element which needs to be moved
_item = ele;
ele_x = mouse_x - _item.offsetLeft;
ele_y = mouse_y - _item.offsetTop;
}
</script>
</head>
<body onload="move_init();">
<div id="ele" onMouseDown="_move_item(this);" style="width:100px; height:100px; background-color: gray; position:fixed;">
<select onmousedown="">
<option>Oh</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
</body>
</html>
Would you please help me to fix the code...

var draggable = function(element) {
element.addEventListener('mousedown', function(e) {
e.stopPropagation();
// if the current target is different (in the case of a child node), don't drag.
// you can customize this to specify types of children which prevent dragging
if (e.target != element)
return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
function move(e) {
element.style.left = (e.pageX - offsetX) + 'px';
element.style.top = (e.pageY - offsetY) + 'px';
}
function stop(e) {
// remove the event listeners on the document when not dragging
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', stop)
}
document.addEventListener('mousemove', move)
document.addEventListener('mouseup', stop)
})
}
function init() {
var ele = document.getElementById('ele');
draggable(ele)
}
This may not work in some IE versions, but you should be able to add the necessary fixes for that. Here's the fiddle http://jsfiddle.net/seKbz/2/

Related

Image mover with javascript does not work properly

Because of an oversized image I want to make it scrollable in the browser window. Scrolling should work in two ways: a) via scroll bars and b) by mouse action. The latter one should work like dragging the image in the direction wanted. So I built a script and attached it to the image. Although the code looks correct it does not work properly. The image sometimes disappears or jumps to an unwanted position. You can invoke the script under
http://ardent.de/JS/
and the code is attached. Does anybody know the reason for the image jumping or disappearing? I'd be glad to receive an answer.
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<img src="schloss.jpg" id="image" />
<script>
var div=document.getElementById('image');
var iwidth,iheight,oldY,oldX,newX, newY;
var mouseisdown=false;
div.addEventListener('load', function() {
iwidth=this.naturalWidth;
iheight=this.naturalHeight;
});
function getCoordinates(elem) {
var LeftPos = elem.offsetLeft;
var TopPos = elem.offsetTop;
return {X:LeftPos,Y:TopPos};
}
function addListeners() {
div.addEventListener('mousedown', mouseDown, false);
div.addEventListener('mouseup', mouseUp, false);
window.addEventListener('mousemove', divMove, false);
var p=getCoordinates(div);oldX = p.X;oldY = p.Y;
}
function mouseUp() {
mouseisdown=false;
}
function mouseDown() {
mouseisdown=true;
}
function divMove(e){
if (mouseisdown) {
div.style.position = 'absolute';
newY=e.clientY-oldY;
newX=e.clientX-oldX;
div.style.top = newY + 'px';
div.style.left = newX + 'px';
oldY=newY;
oldX=newX;}
}
addListeners();
</script>
</body>
</html>
This logic is incorrect:
newY=e.clientY-oldY;
newX=e.clientX-oldX;
...
oldY=newY;
oldX=newX;
Let say your oldX is 0 at start. e.clientX may be 1920 in a full hd screen.
newX value could be jumping from 0 to 1920 because:
newX=e.clientX-oldX; // 1920 - 0
oldX=newX; // 1920
... // Next tick
newX = e.clientX - oldX; // 1920 - 1920
oldX=newX; // 0
So basically this is why the image is jumping from two odd positions.
This is now the improved code. The usage of global variables has been reduced and only two, oldX/Y, remain. My first logical error with the positioning has been corrected. The other problem was the drag behavior of the image, which inhibited the mouseup event. So I set draggable to false and now it works fine in the Chrome browser. Also I had to consider the order of img... and script... which is crucial sometimes, if there is a reference between both tags. Now look at http://ardent.de/JS/ and move the image by pressing the mouse button and moving the mouse.
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="image" onmousedown="mouseDown();" onmouseup="mouseUp();">
<img src="schloss.jpg" draggable="false" />
</div>
<script>
var oldY,oldX;
function getCoordinates(elem) {
var LeftPos = elem.offsetLeft;
var TopPos = elem.offsetTop;
return {X:LeftPos,Y:TopPos};
}
function mouseUp() {
document.removeEventListener('mousemove', mouseMove, false);
document.removeEventListener('mouseup', mouseUp, false);
}
function mouseDown() {
document.addEventListener('mousemove', mouseMove, false);
document.addEventListener('mouseup', mouseUp, false);
oldY=-1; oldX=-1;
}
function mouseMove(e){
var iwidth,iheight,newX, newY, diffX, diffY;
var div=document.getElementById('image');
div.style.position = 'absolute';
if (oldX==-1) {
diffX=0;diffY=0;}
else {
diffY=e.clientY-oldY;diffX=e.clientX-oldX;}
var p=getCoordinates(div);
newY=p.Y+diffY;newX=p.X+diffX;
div.style.top = newY + 'px';div.style.left = newX + 'px';
oldY=e.clientY;oldX=e.clientX;
}
</script>
</body>
</html>

javascript working with mouse events

How can I get the image to be dragged around just if the mouse is clicked, not just follow the mouse around as it is doing right now.
<head>
<style>
#flying {
position: absolute;
}
</style>
<script type="text/javascript">
function UpdateFlyingObj (event) {
var mouseX = Math.round (event.clientX);
var mouseY = Math.round (event.clientY);
var flyingObj = document.getElementById ("flying");
flyingObj.style.left = mouseX + "px";
flyingObj.style.top = mouseY + "px";
}
this.onmouseup = function() {
document.onmousemove = null
}
</script>
</head>
<body onmousemove="UpdateFlyingObj (event);" >
<h1><center>Homework 13.7<center></h1>
<div style="height:1000px;"></div>
<img id="flying" src="flying.gif" />
</body>
The key-point that needs to be considered is handling the ondragstart event of the image. Failing to return false from it means that the browser absorbs the event and gives odd behaviour. See comment in the source.
Try this on for size. (dont forget to change the image-path)
<!DOCTYPE html>
<html>
<head>
<style>
#flying
{
position: absolute;
}
</style>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', myInitFunc, false);
function myInitFunc()
{
byId('flying').addEventListener('mousedown', onImgMouseDown, false);
}
function onImgMouseDown(e)
{
e = e || event;
var mElem = this;
var initMx = e.pageX;
var initMy = e.pageY;
var initElemX = this.offsetLeft;
var initElemY = this.offsetTop;
var dx = initMx - initElemX;
var dy = initMy - initElemY;
document.onmousemove = function(e)
{
e = e || event;
mElem.style.left = e.pageX-dx+'px';
mElem.style.top = e.pageY-dy+'px';
}
this.onmouseup = function()
{
document.onmousemove = null;
}
// try to comment-out the below line
// doing so means the browser absorbs the ondragstart event and (in Chrome) drags a reduced-opacity copy of
// the image, overlaid with a circle that has a diagonal line through it. - just like the usuall behaviour for
// dragging an image on a webpage.
this.ondragstart = function() { return false; }
}
</script>
</head>
<body>
<h1><center>Homework 13.7<center></h1>
<img id="flying" src="img/opera.svg"/>
</body>
</html>

Trying to move boxes

I have a random amount of boxes, randomly on a page of random colors. I am trying to be able to get them to move from one place to another.
Essentially, I am not familiar at all with mouse move events so this is quite the challenge. Even though it is quite simple.
Heres the code for the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ramdom Boxes</title>
<script src="A2Q1.js"></script>
</head>
<body>
</body>
</html>
Javascript:
window.onload = init;
function init() {
//when page is loaded create a bunch of boxes randomly throughout the page
//get the body element of the document
var body = document.getElementsByTagName("body")[0];
//store width and height of boxes
var boxWidth = 50;
var boxHeight = 50;
//create the random number for the boxes
var randNum = Math.floor(Math.random() * 500 + 1);
//create the boxes
for(var i=0;i<randNum;i++){
//create the random color and random positions
var colour = Math.round(0xffffff * Math.random()).toString(16);
var pos1 = Math.floor(Math.random() * window.innerWidth)
var pos2 = Math.floor(Math.random() * window.innerHeight)
// Define an array of css attributes
var attr =[
// Assign a colour to the box
'background-color:#' + colour,
// Place the box somewhere inside the window
'left:' + pos1 + 'px',
'top:' + pos2 + 'px',
// Set the box size
'width:' + boxWidth + 'px',
'height:' + boxHeight + 'px',
'cursor: pointer;',
'position:absolute;'
];
//join the attributes together
var attributes = attr.join(';');
//create a new div tag
var div = document.createElement("div");
//gives the box a unique id
div.setAttribute("id","box"+i)
//create the design of the box
div.setAttribute("style",attributes);
//add to the body
body.appendChild(div);
}
}
I really have no idea where to start...
Well a start would certainly be getting the mouse position, after that the world is your oyster.
var mousex = 0;
var mousey = 0;
function getXY(e){
if (!e) e = window.event;
if (e)
{
if (e.pageX || e.pageY)
{ // this doesn't work on IE6!! (works on FF,Moz,Opera7)
mousex = e.pageX;
mousey = e.pageY;
go = '[e.pageX]';
if (e.clientX || e.clientY) go += ' [e.clientX] '
}
else if (e.clientX || e.clientY)
{ // works on IE6,FF,Moz,Opera7
mousex = e.clientX + document.body.scrollLeft;
mousey = e.clientY + document.body.scrollTop;
go = '[e.clientX]';
if (e.pageX || e.pageY) go += ' [e.pageX] '
}
}
}
With the mouse info you can then do this in another function.
function moveBoxes(){
document.body.onmousemove = updater; //or some container div!
updater();
}
function updater(e){
getXY(e);
document.getElementById('aboxid').style.left=mousex+'px';
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>MouseDown MouseUp</title>
<meta charset="UTF-8">
<style>
#insideBox{
height: 100px;
width: 100px;
background-color: black;
left:300px;
top:300px;
position:absolute;
}
</style>
<script>
var mouseFire = null;
window.onload = init;
function init(){
var div = document.getElementById("insideBox");
div.addEventListener("mousedown",mouseDrag,false);
}
function mouseDrag(e){
var evt = e || window.event;
mouseFire = evt.target || evt.srcElement;
document.addEventListener("mousemove",mouseMove,false);
document.addEventListener("mouseup",mouseDrop,false);
}
function mouseMove(e){
var evt = e || window.event;
var mouseX = evt.clientX;
var mouseY = evt.clientY;
mouseFire.style.left = mouseX-50+"px";
mouseFire.style.top = mouseY-50+"px";
}
function mouseDrop(e){
mouseFire = null;
document.removeEventListener("mousemove",mouseMove,false);
}
</script>
</head>
<body>
<div id="insideBox"></div>
</body>
</html>

Drawing a rectangle using click, mouse move, and click

I'm trying to draw a rectangle by a user click, mouse move, and click. There are two problems with my code.
Firstly, after one rectangle is drawn it is automatically assumed that another one will be drawn. Secondly, the starting point on the second rectangle is the last click that created the first rectangle.
http://jsbin.com/uqonuw/3/edit
You were close. So, the question isn't really about the "canvas" element in HTML5, but a canvas that is really a div.
http://jsfiddle.net/d9BPz/546/
In order for me to see what your code was trying to accomplish, I had to tidy it up. What needed to happen was tracking of the square element.
We are doing one of two things everytime we click on the canvas. We are either creating a rectangle element, or finishing a rectangle element. So, when we're finished it makes sense to set 'element' (previously named 'd') to null. When creating an element, we have to assign the new DOM element to 'element'.
Everytime the mouse moves, we want to get the mouse position. If the element is in the process of creation (or "not null"), then we need to resize the element.
Then we wrap it all up in a function, and that's all there is to it:
function initDraw(canvas) {
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
Usage: Pass the block-level element that you would like to make a rectangle canvas.
Example:
<!doctype html>
<html>
<head>
<style>
#canvas {
width:2000px;
height:2000px;
border: 10px solid transparent;
}
.rectangle {
border: 1px solid #FF0000;
position: absolute;
}
</style>
</head>
<body>
<div id="canvas"></div>
<script src="js/initDraw.js"></script>
<script>
initDraw(document.getElementById('canvas'));
</script>
</body>
</html>
Here's how to click-move-click to create a rectangle
Create these variables:
var isDrawing=false;
var startX;
var startY;
In your mousedown event handler:
If this is the starting click, set the isDrawing flag and set the startX/Y.
If this is the ending click, clear the isDrawing flage and draw the rectangle.
You might also want to change the mouse cursor so the user knows they are drawing.
if(isDrawing){
isDrawing=false;
ctx.beginPath();
ctx.rect(startX,startY,mouseX-startX,mouseY-startY);
ctx.fill();
canvas.style.cursor="default";
}else{
isDrawing=true;
startX=mouseX;
startY=mouseY;
canvas.style.cursor="crosshair";
}
Here is a Fiddle: http://jsfiddle.net/m1erickson/7uNfW/
Instead of click-move-click, how about using drag to create a rectangle?
Create these variables:
var mouseIsDown=false;
var startX;
var startY;
In your mousedown event handler, set the mouseIsDown flag and set the startX/Y.
Optionally, change the cursor so the user knows their dragging a rectangle.
mouseIsDown=true;
startX=mouseX;
startY=mouseY;
canvas.style.cursor="crosshair";
In your mouseup event handler, clear the mouseIsDown flag and draw the rect
If you changed the cursor, change it back.
mouseIsDown=false;
ctx.beginPath();
ctx.rect(startX,startY,mouseX-startX,mouseY-startY);
ctx.fill();
canvas.style.cursor="default";
For those who encountered the scrolling problem, I've found a fix.
You need to get the offset (using window.pageYOffset) and reduce it from the mouse position in any of the recommended snippets given. You should take it off from the height as well.
i was also working on a project, so here's my code
enjoy.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Selection</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<style>
body {
margin: 0px;
background-color: #f1f1f1;
}
canvas {
border: none;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="500"></canvas>
<div id="output"></div>
<script>
//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
//Mousedown
$(canvas).on('mousedown', function(e) {
last_mousex = parseInt(e.clientX-canvasx);
last_mousey = parseInt(e.clientY-canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function(e) {
mousedown = false;
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
//Mousemove
$(canvas).on('mousemove', function(e) {
mousex = parseInt(e.clientX-canvasx);
mousey = parseInt(e.clientY-canvasy);
if(mousedown) {
ctx.clearRect(0,0,canvas.width,canvas.height); //clear canvas
ctx.beginPath();
var width = mousex-last_mousex;
var height = mousey-last_mousey;
ctx.rect(last_mousex,last_mousey,width,height);
//ctx.fillStyle = "#8ED6FF";
ctx.fillStyle = 'rgba(164, 221, 249, 0.3)'
ctx.fill();
ctx.strokeStyle = '#1B9AFF';
ctx.lineWidth = 1;
ctx.fillRect(last_mousex, last_mousey, width, height)
ctx.stroke();
}
//Output
$('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);
});
</script>
</body>
</html>
Below is the solution I created in React. There might be some corner cases but it is working as per my knowledge.
Solution approach.
You must have start (x,y position) and the end (x,y) position
Once the user clicks on the cell capture cell number and column number start (x,y), this will happen on the mouseDown event
Then the user starts moving the mouse, in that case capture the cell number and the row number end (x,y) respectively.
Now the div draw logic comes where the condition would highlight the cell if the below condition is true.
i = cellNumber
i >= Math.min(start,end) && i <= Math.max(start,end) && i%4 <= Math.max(startY, endY)
https://codesandbox.io/s/still-field-0q760y?file=/src/App.js

Is it possible to get the location/position of the mouse cursor on document load event

Just wondering if its possible to get the x/y location of the mouse from the onload event of the document (before any mousemove events)?
short answer: no
long answer: yes. the onload event doesn't provide info on the mouse position, however you can set a variable when onload has fired, and use the onmousemove event on the document to get the mouseposition as soon as the mouse moves after the documents loads (after the variable has been set). Not what you wanted, though.
You can try something like:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script type="text/javascript">
function SetValues() {
var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
getMouseXY();
var mX = 0;
var mY = 0;
function getMouseXY(e) {
if (IE) {
mX = event.clientX + document.body.scrollLeft;
mY = event.clientY + document.body.scrollTop;
}
else {
mX = e.pageX;
mY = e.pageY;
}
var s = 'X=' + mX + ' Y=' + mY ;
document.getElementById('divCoord').innerHTML = s;
return true;
}
}
</script></head>
<body onload=SetValues()>
<div id="divCoord"></div>
</body></html>

Categories

Resources