javascript working with mouse events - javascript

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>

Related

XY coords following cursor movements

i am looking to have this cursor effect on the body:
https://www.screenshot-magazine.com/
i do have two separate codes, one for the bloc following the mouse and another to get the xy coords.
But i am too beginner to merge both together or make both work in parallel to have the XY coods printed in the box following my cursor moves.
Someone could help me?
Thanks a lot in advance:)
Anto
here the two codes:
1-bloc following mouse movements
<style>
#divtoshow {
position:absolute;
display:none;
color: #C0C0C0;
background-color: none;
}
<script type="text/javascript">
var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
var offX = 15; // X offset from mouse position
var offY = 15; // Y offset from mouse position
function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}
function follow(evt) {
var obj = document.getElementById(divName).style;
obj.left = (parseInt(mouseX(evt))+offX) + 'px';
obj.top = (parseInt(mouseY(evt))+offY) + 'px';
}
document.onmousemove = follow;
</script>
<body>
<div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>
<div id="divtoshow">test</div>
2-get XY coords on body
<script>
function readMouseMove(e){
var result_x = document.getElementById('x_result');
var result_y = document.getElementById('y_result');
result_x.innerHTML = e.clientX;
result_y.innerHTML = e.clientY;
}
document.onmousemove = readMouseMove;
</script>
</head>
<body>
<h2 id="x_result">0</h2>
<h2 id="y_result">0</h3>
</body>
Your CSS is fine. You could have moved #x-result and #y-result into #divtoshow, and then set the left and right in readMouseMove. I've modified your code a bit. I'll explain it on the way
const xResult = document.getElementById("x-result");
const yResult = document.getElementById("y-result");
const divToShow = document.getElementById("divtoshow");
document.onmousemove = function (e) {
let mouse = {
x: e.clientX, // this is 2018, so you can just directly use clientX
y: e.clientY // and clientY
};
divToShow.style.left = `${mouse.x + 16}px`; // add a padding so that the text is not rendered directly below the mouse
divToShow.style.top = `${mouse.y + 16}px`;
xResult.innerHTML = `X: ${mouse.x}`; // write the text into the output divs
yResult.innerHTML = `Y: ${mouse.y}`;
};
#divtoshow {
color: #C0C0C0;
position: absolute;
}
<div id="divtoshow">
<span id="x-result">X: 0</span> <br> // i changed the h2s to spans because h2s have HUGE text
<span id="y-result">Y: 0</span>
</div>
You can add the #onme integration by yourself.

resizable and draggable div with fixed surface area

Is it possible to make a resizable and draggable div with a fixed surface area?
Example: I have a square div with a surface area of 10000px² (100 x 100px) and then I change the width (with the mouse on the corner or on the edge) to 50px, the heigth should now change automaticly to 200px so the surface area stays 10000px².
Then I´d like to drag it all over the page, resize it again etc...
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-
ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-
ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#draggable { width: 100px; height: 100px; padding: 0.5em; border:
1px solid;}
</style>
<script>
$(function() {
$( "#draggable" ).draggable().resizable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
</body>
</html>
ok, so here is the code, I have resizable and draggable div but now I need the fixed surface area (eg 10000px²) as I mentioned before...
you can use jquery's UI to do all of this.
use http://jqueryui.com/draggable/ to allow for dragging,
use http://jqueryui.com/resizable/ to allow for resizing
using the resize event, you can have jquery modify the div so it will follow any height/width rules you want.
Try this:
(function(draggable) {
var elm = document.getElementById(draggable);
elm.onmousedown = drag;
function stop() {
document.onmouseup = null;
document.onmousemove = null;
}
function drag(e) {
if (e.target == elm) {
var absX = e.clientX;
var absY = e.clientY;
var left = parseInt(getComputedStyle(elm).left, 10);
var top = parseInt(getComputedStyle(elm).top, 10);
var relX = absX - left;
var relY = absY - top;
document.onmouseup = stop;
document.onmousemove = function(e) {
var absX = e.clientX;
var absY = e.clientY;
elm.style.left = absX - relX + "px";
elm.style.top = absY - relY + "px";
}
}
}
})("box");
(function(resizeable) {
var elm = document.getElementById(resizeable);
var wHandler = elm.childNodes[1];
var hHandler = elm.childNodes[3];
wHandler.onmousedown = resizeW;
hHandler.onmousedown = resizeH;
function stop() {
elm.style.cursor = "";
document.body.style.cursor = "";
document.onmouseup = null;
document.onmousemove = null;
}
var w = 100;
var h = 100;
var area = w * h;
function resizeW(e) {
elm.style.cursor = "w-resize";
document.body.style.cursor = "w-resize";
var left = parseInt(window.getComputedStyle(elm, null)["left"], 10);
document.onmouseup = stop;
document.onmousemove = function(e) {
var absX = e.clientX;
var width = absX - left;
var height = area / width;
elm.style.width = width + "px";
elm.style.height = height + "px";
}
}
function resizeH(e) {
elm.style.cursor = "n-resize";
document.body.style.cursor = "n-resize";
var top = parseInt(window.getComputedStyle(elm, null)["top"], 10);
document.onmouseup = stop;
document.onmousemove = function(e) {
var absY = e.clientY;
var height = absY - top;
var width = area / height;
elm.style.height = height + "px";
elm.style.width = width + "px";
}
}
})("box");
Fiddle
Though there's a small bug, I think. Couldn't fix it. When you resize the width it's ok, but when you resize the height, and then move the div, it lags or w/e. Check the fiddle. Other than this, it's working fine.

Javascript addEventListener does it matter what the name of the function is in the second parameter?

Does it matter what the name of the function is in the second parameter of the addEventListern(Parm1, Parm2, Parm3)
I think that the error might have been because not all of the calls were renamed to that specific function name. There are a couple of times when that function is called and I think that would be what probably is causing the errors.
My code works with the below code. You can drag the circle around the canvas.
theCanvas.addEventListener("mousedown", mouseDownListener, false);
But if I change the code to the following.
theCanvas.addEventListener("mousedown", er, false);
And also rename the mouseDownListener method to er I can drag the circle around but when I release the mouse the circle keeps following the mouse pointer around. This seems like an odd behavior and I am not certain as to why this would be.
Question: Does the second parameter function name have to be mouseDownListener exactly or can this be an ad hoc name?
HTML Code:
<!doctype html>
<html lang="en">
<head>
<style type="text/css">
h4 {font-family: sans-serif;}
p {font-family: sans-serif;}
a {font-family: sans-serif; color:#d15423; text-decoration:none;}
</style>
<title>HTML5 Canvas Example - Simple Dragging Objects</title>
<script type="text/javascript">
window.addEventListener("load", canvasApp, false);
var Debugger = function() { };
Debugger.log = function(message) {
try {
console.log(message);
}
catch (exception) {
return;
}
}
function canvasApp() {
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
init();
var numShapes;
var shapes;
var dragIndex;
var dragging;
var mouseX;
var mouseY;
var dragHoldX;
var dragHoldY;
function init() {
numShapes = 1;
shapes = [];
makeShapes();
drawScreen();
theCanvas.addEventListener("mousedown", mouseDownListener, false);
}
function makeShapes() {
var i;
var tempX;
var tempY;
var tempRad;
var tempR;
var tempG;
var tempB;
var tempColor;
for (i=0; i < numShapes; i++) {
tempRad = 10 + Math.floor(Math.random()*25);
tempX = Math.random()*(theCanvas.width - tempRad);
tempY = Math.random()*(theCanvas.height - tempRad);
tempR = Math.floor(Math.random()*255);
tempG = Math.floor(Math.random()*255);
tempB = Math.floor(Math.random()*255);
tempColor = "rgb(" + tempR + "," + tempG + "," + tempB +")";
tempShape = {x:tempX, y:tempY, rad:tempRad, color:tempColor};
shapes.push(tempShape);
}
}
//main function for when the mouse button is clicked -- Once everything is loaded everything depends on this function
function mouseDownListener(evt) {
var i;
var highestIndex = -1;
var bRect = theCanvas.getBoundingClientRect();
mouseX = (evt.clientX - bRect.left)*(theCanvas.width/bRect.width);
mouseY = (evt.clientY - bRect.top)*(theCanvas.height/bRect.height);
//find which shape was clicked
for (i=0; i < numShapes; i++) {
if (hitTest(shapes[i], mouseX, mouseY)) {
dragging = true;
if (i > highestIndex) {
dragHoldX = mouseX - shapes[i].x;
dragHoldY = mouseY - shapes[i].y;
highestIndex = i;
dragIndex = i;
}
}
}
if (dragging) {
window.addEventListener("mousemove", mouseMoveListener, false);
}
theCanvas.removeEventListener("mousedown", mouseDownListener, false);
window.addEventListener("mouseup", mouseUpListener, false);
if (evt.preventDefault) {
evt.preventDefault();
} //standard
else if (evt.returnValue) {
evt.returnValue = false;
} //older IE
return false;
}
function mouseUpListener(evt) {
theCanvas.addEventListener("mousedown", mouseDownListener, false);
window.removeEventListener("mouseup", mouseUpListener, false);
if (dragging) {
dragging = false;
window.removeEventListener("mousemove", mouseMoveListener, false);
}
}
function mouseMoveListener(evt) {
var posX;
var posY;
var shapeRad = shapes[dragIndex].rad;
var minX = shapeRad;
var maxX = theCanvas.width - shapeRad;
var minY = shapeRad;
var maxY = theCanvas.height - shapeRad;
var bRect = theCanvas.getBoundingClientRect();
mouseX = (evt.clientX - bRect.left)*(theCanvas.width/bRect.width);
mouseY = (evt.clientY - bRect.top)*(theCanvas.height/bRect.height);
posX = mouseX - dragHoldX;
posX = (posX < minX) ? minX : ((posX > maxX) ? maxX : posX);
posY = mouseY - dragHoldY;
posY = (posY < minY) ? minY : ((posY > maxY) ? maxY : posY);
shapes[dragIndex].x = posX;
shapes[dragIndex].y = posY;
drawScreen();
}
function hitTest(shape,mx,my) {
var dx;
var dy;
dx = mx - shape.x;
dy = my - shape.y;
return (dx*dx + dy*dy < shape.rad*shape.rad);
}
function drawShapes() {
var i;
for (i=0; i < numShapes; i++) {
context.fillStyle = shapes[i].color;
context.beginPath();
context.arc(shapes[i].x, shapes[i].y, shapes[i].rad, 0, 2*Math.PI, false);
context.closePath();
context.fill();
}
}
function erraseCanvas() {
context.clearRect(0,0,theCanvas.width,theCanvas.height);
}
function clearTheScreenWithRectangle() {
context.fillStyle = "#000000";
context.fillRect(0,0,theCanvas.width,theCanvas.height);
}
function drawScreen() {
//erraseCanvas();
clearTheScreenWithRectangle();
drawShapes();
}
}
</script>
</head>
<body>
<div style="top: 50px; text-align:center">
<canvas id="canvasOne" width="1000" height="500">
Your browser does not support HTML5 canvas.
</canvas>
</div>
</body>
</html>
The second parameter has to be a reference to the function you want called when the event is triggered.
When passing a function, you may call it any, valid javascript identifier.
The second function can be called anything. The behaviour you describe by renaming the function to er could be caused if you forget to rename every occurrence of the function name (especially where it is disabled etc)
No, ceiling cat does not force you to set your function names to anything. You have freedom to name it whatever you like.
The second parameter is just a reference to the function you defined earlier, you can put any function (even anonymous) there.
The second parameter in in this statement can be any valid javascript name.
window.addEventListener("load", canvasApp, false);
Can be any valid name in Javascript that you want it to me.
window.addEventListener("load", ILoveBaseballANDApplePie, false);
window.addEventListener("load", Pizza, false);
window.addEventListener("load", AnyOtherName, false);
function Pizza() {
//do some code here
}
function ILoveBaseballANDApplePie() {
//do some code here
}
For programming purposes I would add the "load" name to the function name some how just so that 2 years later you will remember that that the function has to do with the load parameter. I would purchase a simple book on Javascript and use Notepad++ to go through some simple examples because even after using Javascript for the past 6 months I still find it somewhat of a beast to contend with on some things. With HTML5 you will be using these events probably a lot so I would learn as much as I possibly could about Javascript events.

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>

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

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/

Categories

Resources