I am creating a canvas alike without using canvas tag , by creating new div each time mouse is down, i can't figure out how to run a second event.
Like mousedown then mousemove event where the seconed event occur only after the first one is true?
also if you can help with the offset coordinates
var paintbox = document.getElementById("canvas");
var start = function() {
paintbox.addEventListener("mousedown", drawOnCanvas);
};
var newColor = document.getElementById("colorPick");
var drawOnCanvas = function() {
var newClick = document.createElement("div");
newClick.setAttribute("id", "smallDiv");
newClick.style.backgroundColor = newColor.value;
newClick.style.width = "10px";
newClick.style.height = "10px";
newClick.style.position = "absolute";
paintbox.appendChild(newClick);
}
Set the handler on the mousemove event instead of mousedown and in the handler check whether the mouse button is down.
It would be better to move the 10px/position style settings in a CSS class. Also, don't generate elements with the same id attribute value: that generates invalid HTML. Use a class instead.
For the positioning you can use the pageX and pageY properties of the event object.
Finally, as the events will be triggered on the small divs when you make small moves, an extra check might be necessary to verify the mouse is still in the paint box.
var paintbox = document.getElementById("canvas");
var start = function() {
paintbox.addEventListener("mousemove", drawOnCanvas);
};
var newColor = document.getElementById("colorPick");
var drawOnCanvas = function(e) {
if ((e.buttons & 1) === 0) return; // Mouse button is not down
// Extra check to see we are well within the box boundaries:
var box = paintbox.getBoundingClientRect();
if (e.clientX - 5 < box.left || e.clientX + 5 > box.right
|| e.clientY - 5 < box.top || e.clientY + 5 > box.bottom) return;
var newClick = document.createElement("div");
newClick.className = "smallDiv"; // Don't create duplicate ID; put CSS in class
newClick.style.backgroundColor = newColor.value;
paintbox.appendChild(newClick);
newClick.style.left = (e.pageX-5) + "px";
newClick.style.top = (e.pageY-5) + "px";
}
start();
#canvas {
height: 150px;
width: 300px;
border: 1px solid;
display: inline-block;
margin: 10px;
}
.smallDiv {
width: 10px;
height: 10px;
position: absolute;
}
Color: <input id="colorPick" type="color"><br>
<div id="canvas"></div>
Related
I am looking to select items in a web page using the LeapMotion and I am struggling with programming this interaction.
Using this code as a base (but updating the link so it connects to the current SDK) I can get my cursor to move around the window based on where my hand is in space. However, I do not know how to make the equivalent of the event listener "click" using the LeapMotion. I am using Leap.js and have built a crude GUI using svg.js.
How do I program an event listener that selects using the LeapMotion in Javascript?
I have working code with Leap motion. I did quize software. Here cursor is a div element which styled as:
#cursor {
width: 60px;
height: 60px;
position: fixed;
margin-left: 20px;
margin-top: 20px;
z-index: 99999;
opacity: 0.9;
background: black;
border-radius: 100%;
background: -webkit-radial-gradient(100px 100px, circle, #f00, #ff6a00);
background: -moz-radial-gradient(100px 100px, circle, #f00, #ff6a00);
background: radial-gradient(100px 100px, circle, #f00, #ff6a00);
}
and Java script at bottom. What I did, I get HTML element by position and triggering click event on it by tap gestures.
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
// Setting cursor and output position
window.cursor = $('#cursor');
var controller= Leap.loop(function(frame) {
if (frame.pointables.length > 0) {
try
{
var position = frame.pointables[0].stabilizedTipPosition;
var normalized = frame.interactionBox.normalizePoint(position);
var cx = w * normalized[0];
var cy = h * (1 - normalized[1]);
$('#cursor').css('left', cx);
$('#cursor').css('top', cy);
}catch(e){
console.error(e);
}
}
});
controller.use('screenPosition', {
scale: 1
});
controller.on('gesture', onGesture);
function onGesture(gesture,frame)
{
try
{
// If gesture type is keyTap
switch(gesture.type)
{
case 'keyTap':
case 'screenTap':
var position = frame.pointables[0].stabilizedTipPosition;
var normalized = frame.interactionBox.normalizePoint(position);
//Hiding cursor for getting background element
cursor.hide();
// Trying find element by position
var cx = w * normalized[0];
var cy = h * (1 - normalized[1]);
var el = document.elementFromPoint(cx, cy);
cursor.show();
console.log(el);
if (el) {
$(el).trigger("click");
}
break;
}
}
catch (e) {
console.info(e);
}
}
I have implemented the drag and drop API of HTML5 in my app, and I need to disable the default ghost image when the user drag an item.
The items aren't images but row from a table like :
<table>
<tr draggable droppable ><td></td></tr>
<tr draggable droppable ><td></td></tr>
<tr draggable droppable ><td></td></tr>
</table>
Each row can be draggable in to another one (see it as a filesystem with folder and files).
In my dragstart I've done something like this to hide the default ghost image :
e.originalEvent.dataTransfer.setDragImage(disableImg[0], 0, 0);
Where diableImg is a dom element with 0 width and 0 height opacity 0 etc...
The issue here is that this is not working for IE since it doesn't support the setDragImage.
Is there another way to disable this ghost image of my row on drag ?
I just need to have it working from IE 11 -> Edge.
Thanks.
Example of set custom ghost image in IE.
var ghostImg = document.getElementById("ghostImg");
document.getElementById('dragme').addEventListener('dragstart', function(e) {
var target = e.srcElement || e.target;
var cloneNode = target.cloneNode(true);
target.parentNode.insertBefore(cloneNode, target);
target.style.display = "none";
window.setTimeout(function() {
target.parentNode.removeChild(cloneNode);
target.style.display = "block";
}, 0);
ghostImg.style.zIndex = '99';
ghostImg.style.visibility = 'visible'
ghostImg.style.top = e.clientY + 'px';
ghostImg.style.left = e.clientX + 'px';
})
document.getElementById('dragme').addEventListener('drag', function(e) {
ghostImg.style.zIndex = '99';
ghostImg.style.top = e.clientY + 'px';
ghostImg.style.left = e.clientX + 'px';
});
document.getElementById('dragme').addEventListener('dragend', function(e) {
ghostImg.removeAttribute('style');
});
#dragme {
width: 100px;
height: 100px;
background: #78ebff;
border: 1px solid #56bdff;
text-align: center;
line-height: 100px;
border-radius: 10px;
}
#ghostImg {
position: fixed;
left: 0;
top: 0;
z-index: -1;
visibility: hidden;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="dragme" draggable="true">
Drag me
</div>
<img id="ghostImg" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAVL0lEQVR4Xu2dd3QV1drGnzlnZk4qRQQpgihFgpRIkyI2ulIMlosKAQKigBjwXqQTqn73+y5SBaULXEILTbk0uVKU3gVsNIkgFiAEyCkz58z37FmctTAmIddLYsr+rfWuk8yBP7LeZ7/73e9+9x7FsiwUXiQOFBAkUgASKQCJFIBECkAiBSCRApBIAUikACRSABIpAIkUgEQKQCIFIJECkEgBSKQAJFIAEikAiYocRzJ37tweISEhL3i93jRFUdIApFmWJT6DdoNmf0cT37kDgYDb4XC4AXhofv7uM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lS2c04TJS07TcT/ZyXwAScTJHM/wvmn6zm2UadVVNty+jeC4mxn5jafWoKDhV9b9J9hJuFnesPHxRpERRFJ27jI9zIHX2G2YbWIGSYRGRtgDat2+HV3u+itKl78n9ZC/3BSAJ511+RiDQkid42/l9RmPAKlOpcmVMmzoNrVu3yoFkL08LQE4Rqs/f3TS8I8LDwsIXsA+hY0xMtpM9KYACtNfAqWFpsWLFin+6eZM4mZwDyV6ergTKvQZN1V9lZ7LZ941+4layLCt7BVAAEq83LYnl5Vm7d+0UN5qm38YdT7MK+DuDJIbqGKM4nBffnz5DXE13CsAz6TJ9KYCC3onkVLUZZ86e3d22bdsXAexEHkBFriExfZ53AYzjG8wCuLPIVYBETgESKQCJFIBECkAiBSCRApBIAUikACRSABIpAIkUgEQKQCIFIJECkEgBSKQAJFIAEikAyf8DWKwZjLeDLnkAAAAASUVORK5CYII="/>
</body>
</html>
On dragStart event, implement:
function dragStart(e)
{
var target = e.srcElement || e.target;
if (isIEBrowser()) // check its IE browser
{
var cloneNode = target.cloneNode(true);
target.parentNode.insertBefore(cloneNode, target);
target.style.visibility = "collapse";
window.setTimeout(() => {
target.parentNode.removeChild(cloneNode);
target.style.visibility = "visible";
}, 0);
}
}
I was having this problem as well. I simply set the display to none before the drag.
if (event.dataTransfer.setDragImage)
{
let dragImage = document.createElement("div");
dragImage.style.visibility = "hidden";
event.dataTransfer.setDragImage(dragImage, 0, 0);
}
else
{
//Well if we cannot remove the ghost image then we need to make the initial image invisible when a ghost image would be captured
//then make the item visible again.
var initialDisplay = event.srcElement.style.display;
event.srcElement.style.display = "none";
window.setTimeout(() =>
{
event.srcElement.style.display = initialDisplay;
});
}
Seems after 1 frame (notice the settimeout doesn't specify a delay time) the display went back to normal, but when the ghost image was captured it was invisible.
I am trying to do a simple Range/Value Slider by using javascript or jQuery, A button in a div.This slider should be done without bootstrapor any other pluginor with inbuild functions
My question is how to move the slider button within the div element and what mouse events are needed to do this?
Note:This is not a slideshow slider or image slider
Take a look at this simple slider implementation. Feel free to use and modify the way you prefer:
document.addEventListener('DOMContentLoaded', function() {
var sliders = document.querySelectorAll('.my-slider');
[].forEach.call(sliders, function(el, i) {
var btn = el.firstElementChild,
span = el.nextElementSibling.querySelector('span'),
isMoving = false;
var move = function(e) {
if (isMoving) {
var min = 0,
max = el.offsetWidth - btn.offsetWidth,
mousePos = (e.pageX - el.offsetLeft - (btn.offsetWidth / 2)),
position = (mousePos > max ? max : mousePos < min ? min : mousePos),
value = Math.floor((position / max) * 100);
btn.style.marginLeft = position + 'px';
btn.value = value;
span.textContent = value;
}
};
el.addEventListener('mousedown', function(e) {
isMoving = true;
move(e);
});
document.addEventListener('mouseup', function(e) {
isMoving = false;
});
document.addEventListener('mousemove', function(e) {
move(e);
});
});
});
.my-slider {
width: 250px;
border: 1px solid #999;
border-radius: 3px;
background-color: #ccc;
height: 10px;
line-height: 10px;
}
.my-slider__button {
border: 1px solid #333;
border-radius: 3px;
margin-top: -4px;
width: 18px;
height: 18px;
background-color: #eee;
display: block;
}
div {
margin-top: 6px;
}
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
You use drag and drop events, with a property setting that is restricted to the div it is within. Check out this link Drag Drop Reference Guide, and you will see everything you need. When you use draggable and dropable, you can restrict the movement to horizontal, and also set the element that it is bound to. This will allow you to only move left to right, and restrict vertical movement, and keep in the boundaries of the div. The same features bootstrap uses to get it done.
Here is a basic example showing some of the stuff mentioned:
$('. draggable').draggable({
axis: 'y',
handle: '.top'
drag: function( event, ui ) {
var distance = ui.originalPosition.top - ui.position.top;
// if dragged towards top
if (distance > 0) {
//then set it to its initial state
$('.draggable').css({top: ui.originalPosition.top + 'px'});
}
}
});
try this :
$('img').mouseenter(function(){ //or you can use hover()
// Set the effect type
var effect = 'slide';
// Set the options for the effect type chosen
var options = { direction: "right" };
// Set the duration (default: 400 milliseconds)
var duration = 1000;
$(this).toggle(effect, options, duration);
});
I'm trying to build a draggable column based layout in JavaScript and having a bit of hard time with it.
The layout comprises of 3 columns (divs), with two dragable divs splitting each. The idea is that they are positioned absolutely and as you drag the draggers, the columns' respective widths, and left values are updated.
The three columns should always span the full width of the browser (the right most column is 100% width), but the other two should remain static by default when the browser is resized (which is why i'm using px, not %).
My code isn't working as of yet, I'm relatively new to JavaScript (which is why I don't want to use jQuery).
Having said that, there must be a more efficient (and cleaner) way of achieving this with less code that works (without reaching for the $ key).
If anyone with some awesome JS skills can help me out on this I'd be super-appreciative.
Here's the fiddle I'm working on http://jsfiddle.net/ZFwz5/3/
And here's the code:
HTML
<!-- colums -->
<div class="col colA"></div>
<div class="col colB"></div>
<div class="col colC"></div>
<!-- draggers -->
<div class="drag dragA" style="position: absolute; width: 0px; height: 100%; cursor: col-resize; left:100px;"><div></div></div>
<div class="drag dragB" style="position: absolute; width: 0px; height: 100%; cursor: col-resize; left: 300px;"><div></div></div>
CSS:
body {
overflow:hidden;
}
.col {
position: absolute;
height:100%;
left: 0;
top: 0;
overflow: hidden;
}
.colA {background:red;width:100px;}
.colB {background:green; width:200px; left:100px;}
.colC {background:blue; width:100%; left:300px;}
.drag > div {
background: 0 0;
position: absolute;
width: 10px;
height: 100%;
cursor: col-resize;
left: -5px;
}
and my terrible JavaScript:
//variabe columns
var colA = document.querySelector('.colA');
var colB = document.querySelector('.colB');
var colC = document.querySelector('.colC');
//variable draggers
var draggers = document.querySelectorAll('.drag');
var dragA = document.querySelector(".dragA");
var dragB = document.querySelector(".dragB");
var dragging = false;
function drag() {
var dragLoop;
var t = this;
var max;
var min;
if (dragging = true) {
if (this == dragA) {
min = 0;
max = dragB.style.left;
} else {
min = dragA.style.left;
max = window.innerWidth;
}
dragLoop = setInterval(function () {
var mouseX = event.clientX;
var mouseY = event.clientY;
if (mouseX >= max) {
mouseX = max;
}
if (mouseY <= min) {
mouseY = min;
}
t.style.left = mouseX;
updateLayout();
}, 200);
}
}
function updateLayout() {
var posA = dragA.style.left;
var posB = dragB.style.left;
colB.style.paddingRight = 0;
colA.style.width = posA;
colB.style.left = posA;
colB.style.width = posB - posA;
colC.style.left = posB;
colC.style.width = window.innerWidth - posB;
}
for (var i = 0; i < draggers.length; i++) {
draggers[i].addEventListener('mousedown', function () {
dragging = true;
});
draggers[i].addEventListener('mouseup', function () {
clearInterval(dragLoop);
dragging = false;
});
draggers[i].addEventListener('mouseMove', function () {
updateLayout();
drag();
});
}
I see a couple of things wrong here. First of all, the mousemove event only fires on an element when the mouse is over that element. You might have better luck registering a mousemove listener on the parent of your div.drag elements, then calculating the mouse's position inside that parent whenever a mouse event happens, then using that position to resize your columns and your draggers.
Second, I'm not quite sure what you're trying to do by registering a function with setInterval. You're doing pretty well with registering event listeners; why not continue to use them to change the state of your DOM? Why switch to a polling-based mechanism? (and the function you pass to setInterval won't work anyway - it refers to a variable named event, which in that context is undefined.)
This is just a little example... I hope it can help you :)
window.onload = function() {
var myDiv = document.getElementById('myDiv');
function show_coords(){
var monitor = document.getElementById('monitor');
var x = event.clientX - myDiv.clientWidth / 2;
var y = event.clientY - myDiv.clientWidth / 2;
monitor.innerText = "X: " + x + "\n" + "Y: " + y;
myDiv.style.left = x + "px";
myDiv.style.top = y + "px";
}
document.onmousemove = function(){
if(myDiv.innerText == "YES"){show_coords();}
}
myDiv.onmousedown = function(){
myDiv.innerText = "YES";
}
myDiv.onmouseup = function(){
myDiv.innerText = "NO";
}
}
I want to use the 'mouse's drag' to drag a background's position around, inside a box.
The CSS:
.filmmakers #map {
width : 920px;
height : 500px;
margin-top : 50px;
margin-left : 38px;
border : 1px solid rgb(0, 0, 0);
cursor : move;
overflow : hidden;
background-image : url('WorldMap.png');
background-repeat : no-repeat;
}
The html:
<div id = "map" src = "WorldMap.png" onmousedown = "MouseMove(this)"> </div>
The Javascript:
function MouseMove (e) {
var x = e.clientX;
var y = e.clientY;
e.style.backgroundPositionX = x + 'px';
e.style.backgroundPositionY = y + 'px';
e.style.cursor = "move";
}
Nothing happens, no errors, no warnings, nothing... I have tried lots of things: an absolutely positioned image inside a div (you can guess why that didn't work), A draggable div inside a div with a background image, a table with drag and drop, and finally I tried this:
function MouseMove () {
e.style.backgroundPositionX = 10 + 'px';
e.style.backgroundPositionY = 10 + 'px';
e.style.cursor = "move";
}
This works, but its not relative to the mouse's position, pageX and pageY don't work either.
A live demo: http://jsfiddle.net/VRvUB/224/
P.S: whatever your idea is, please don't write it in JQuery
From your question I understood you needed help implementing the actual "dragging" behavior. I guess not. Anyway, here's the results of my efforts: http://jsfiddle.net/joplomacedo/VRvUB/236/
The drag only happens when the mouse button, and.. well, it behaves as I think you might want it to. Just see the fiddle if you haven't =)
Here's the code for those who want to see it here:
var AttachDragTo = (function () {
var _AttachDragTo = function (el) {
this.el = el;
this.mouse_is_down = false;
this.init();
};
_AttachDragTo.prototype = {
onMousemove: function (e) {
if ( !this.mouse_is_down ) return;
var tg = e.target,
x = e.clientX,
y = e.clientY;
tg.style.backgroundPositionX = x - this.origin_x + this.origin_bg_pos_x + 'px';
tg.style.backgroundPositionY = y - this.origin_y + this.origin_bg_pos_y + 'px';
},
onMousedown: function(e) {
this.mouse_is_down = true;
this.origin_x = e.clientX;
this.origin_y = e.clientY;
},
onMouseup: function(e) {
var tg = e.target,
styles = getComputedStyle(tg);
this.mouse_is_down = false;
this.origin_bg_pos_x = parseInt(styles.getPropertyValue('background-position-x'), 10);
this.origin_bg_pos_y = parseInt(styles.getPropertyValue('background-position-y'), 10);
},
init: function () {
var styles = getComputedStyle(this.el);
this.origin_bg_pos_x = parseInt(styles.getPropertyValue('background-position-x'), 10);
this.origin_bg_pos_y = parseInt(styles.getPropertyValue('background-position-y'), 10);
//attach events
this.el.addEventListener('mousedown', this.onMousedown.bind(this), false);
this.el.addEventListener('mouseup', this.onMouseup.bind(this), false);
this.el.addEventListener('mousemove', this.onMousemove.bind(this), false);
}
};
return function ( el ) {
new _AttachDragTo(el);
};
})();
/*** IMPLEMENTATION ***/
//1. Get your element.
var map = document.getElementById('map');
//2. Attach the drag.
AttachDragTo(map);
This isn't working because you are passing the element "map" to your MouseMove function, and using it as both an event object and an element. You can fix this painlessly by using JavaScript to assign your event handler rather than HTML attributes:
<div id="map"></div>
And in your JavaScript:
document.getElementById('map').onmousemove = function (e) {
// the first parameter (e) is automatically assigned an event object
var x = e.clientX;
var y = e.clientY;
// The context of this is the "map" element
this.style.backgroundPositionX = x + 'px';
this.style.backgroundPositionY = y + 'px';
}
http://jsfiddle.net/VRvUB/229/
The downside of this approach is that the backgroundPositionX and backgroundPositionY style properties are not supported in all browsers.
You mention "an absolutely positioned image inside a div" which is probably the more compatible solution for this. To make this setup work, you need to set the position of the outer element to relative, which makes absolute child elements use its bounds as zero.
<div id="map">
<img src="" alt="">
</div>
CSS:
#map {
position:relative;
overflow:hidden;
}
#map img {
position:absolute;
left:0;
top:0;
}
Here it is applied to your code: http://jsfiddle.net/VRvUB/232/
This works 100%
Vanilla Javascript
document.getElementById('image').onmousemove = function (e) {
var x = e.clientX;
var y = e.clientY;
this.style.backgroundPositionX = -x + 'px';
this.style.backgroundPositionY = -y + 'px';
this.style.backgroundImage = 'url(https://i.ibb.co/vhL5kH2/image-14.png)';
}
document.getElementById('image').onmouseleave = function (e) {
this.style.backgroundPositionX = 0 + 'px';
this.style.backgroundPositionY = 0 + 'px';
this.style.backgroundImage = 'url(https://i.ibb.co/Ph9MCB2/template.png)';
}
.container {
max-width: 670px;
height: 377px;
}
#image {
max-width: 670px;
height: 377px;
cursor: crosshair;
overflow: hidden;
background-image: url('https://i.ibb.co/Ph9MCB2/template.png');
background-repeat: no-repeat;
}
<div class="container">
<div id="image">
</div>
</div>