I need to modify a pasted image inside a contenteditable div: resize it proportionately, add borders, etc... Perhaps this can be achieved by adding a className that will alter the necessary CSS properties.
The problem is that I don't know how to reference the focused, i.e. the active, the clicked-upon image or any element for that matter.
This is the HTML that I am trying to use
<!DOCTYPE html>
<html>
<body>
<div contenteditable="true">This is a div. It is editable. Try to change this text.</div>
</body>
</html>
Using css, html and javascript
Your editable content should be inside a parent div with an id or class name, you can even have different divs for images and such.
Then it is as simple as having css like so:
#editableContentDiv img {
imgProperty: value;
}
Then you can have javascript like so:
function insertImage(){
var $img = document.querySelector("#editableContentDiv img");
$img.setAttribute('class','resize-drag');
}
Eventually if you have more than one img inside the same div you can use querySelectorAll instead of querySelector and then iterate through the img tags inside same div.
I beleive that should at least give you an idea of where to start with what you want.
Similar example
I found this gist that seems to have similar things to want you want but a bit more complicated.
function resizeMoveListener(event) {
var target = event.target,
x = (parseFloat(target.dataset.x) || 0),
y = (parseFloat(target.dataset.y) || 0);
// update the element's style
target.style.width = event.rect.width + 'px';
target.style.height = event.rect.height + 'px';
// translate when resizing from top or left edges
x += event.deltaRect.left;
y += event.deltaRect.top;
updateTranslate(target, x, y);
}
function dragMoveListener(event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.dataset.x) || 0) + event.dx,
y = (parseFloat(target.dataset.y) || 0) + event.dy;
updateTranslate(target, x, y);
}
function updateTranslate(target, x, y) {
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the position attributes
target.dataset.x = x;
target.dataset.y = y;
}
function insertImage() {
var $img = document.createElement('img');
$img.setAttribute('src', 'https://vignette.wikia.nocookie.net/googology/images/f/f3/Test.jpeg/revision/latest?cb=20180121032443');
$img.setAttribute('class', 'resize-drag');
document.querySelector(".container-wrap").appendChild($img);
var rect = document.querySelector(".container-wrap").getBoundingClientRect();
$img.style.left = rect.left;
$img.style.top = rect.top;
}
function dataTransfer() {
//cleanup
var $out = document.querySelector(".out-container-wrap");
while ($out.hasChildNodes()) {
$out.removeChild($out.lastChild);
}
//get source
var source = document.querySelector('.container-wrap')
//get data
var data = getSource(source);
//add data to target
setSource($out, data);
}
/**
* Get data from source div
*/
function getSource(source) {
var images = source.querySelectorAll('img');
var text = source.querySelector('div').textContent;
//build the js object and return it.
var data = {};
data.text = text;
data.image = [];
for (var i = 0; i < images.length; i++) {
var img = {}
img.url = images[i].src
img.x = images[i].dataset.x;
img.y = images[i].dataset.y;
img.h = images[i].height;
img.w = images[i].width;
data.image.push(img)
}
return data;
}
function setSource(target, data) {
//set the images.
for (var i = 0; i < data.image.length; i++) {
var d = data.image[i];
//build a new image
var $img = document.createElement('img');
$img.src = d.url;
$img.setAttribute('class', 'resize-drag');
$img.width = d.w;
$img.height = d.h;
$img.dataset.x = d.x;
$img.dataset.y = d.y;
var rect = target.getBoundingClientRect();
$img.style.left = parseInt(rect.left);
$img.style.top = parseInt(rect.top);
//transform: translate(82px, 52px)
$img.style.webkitTransform = $img.style.transform = 'translate(' + $img.dataset.x + 'px,' + $img.dataset.y + 'px)';
//$img.style.setProperty('-webkit-transform', 'translate('+$img.dataset.x+'px,'+$img.dataset.y+'px)');
target.appendChild($img);
}
//make a fresh div with text content
var $outContent = document.createElement('div')
$outContent.setAttribute('class', 'out-container-content');
$outContent.setAttribute('contenteditable', 'true');
$outContent.textContent = data.text;
target.appendChild($outContent);
}
interact('.resize-drag')
.draggable({
onmove: dragMoveListener,
inertia: true,
restrict: {
restriction: "parent",
endOnly: true,
elementRect: {
top: 0,
left: 0,
bottom: 1,
right: 1
}
}
})
.resizable({
edges: {
left: true,
right: true,
bottom: true,
top: true
},
onmove: resizeMoveListener
})
.resize-drag {
z-index: 200;
position: absolute;
border: 2px dashed #ccc;
}
.out-container-content,
.container-content {
background-color: #fafcaa;
height: 340px;
}
#btnInsertImage {
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.interactjs.io/interact-1.2.4.min.js"></script>
</head>
<body>
<button id="btnInsertImage" onclick="insertImage()">Insert Image</button>
<div class="container-wrap">
<div class="container-content" contenteditable="true">This is the content of the container. The content is provided along with the image. The image will be moved around and resized as required. The image can move within the boundary of the container.</div>
</div>
<button id="btnSubmit" onclick="dataTransfer()">Submit</button>
<div class="out-container-wrap">
</div>
</body>
</html>
Source
This is what I tried and it seems to be working - at least on my system, the snippet I made does not work unfortunately.
function getSelImg(){
var curObj;
window.document.execCommand('CreateLink',false, 'http://imageselectionhack/');
allLinks = window.document.getElementsByTagName('A');
for(i = 0; i < allLinks.length; i++)
{
if (allLinks[i].href == 'http://imageselectionhack/')
{
curObj = allLinks[i].firstChild;
window.document.execCommand('Undo'); // undo link
break;
}
}
if ((curObj) && (curObj.tagName=='IMG'))
{
//do what you want to...
curObj.style.border = "thick solid #0000FF";
}
}
<!DOCTYPE html>
<html>
<body>
<input type="button" onclick="getSelImg()" value="set img border">
<div contenteditable="true">This is a div.<br>
It is editable.<br>
Try to paste an image here:<br>
###########################<br>
<br>
<br>
<br>
###########################
</div>
</body>
</html>
Related
I want to split multiple images into tiles(it must be div or similar). (With Javascript or jQuery.)
and Images should be one below the other.
Its my div;
<div class="reading-content">
<div class="page-break no-gaps">
<img id="image-0" src="image.jpg" class="some-class">
</div>
<div class="page-break no-gaps">
<img id="image-1" src="image1.jpg" class="some-class">
</div>
</div>
example jsfiddle; http://jsfiddle.net/0Lxr2tad/
var t = Date.now();
var img = new Image();
var length = 30;
var ylength = 20;
img.onload = function() {
var width = this.width,
height = this.height,
_length = -length,
i, j;
// create a <div/> with all basic characteristics, to be cloned over and over in the loops below.
var $basicDiv = jQuery('<div/>', {
class: 'splitImg',
css: {
'width': Math.floor(width/length),
'height': Math.floor(height/ylength),
'background-image': 'url(' + img.src + ')'
}
});
// Finding a node in the DOM is slow. Do it once and assign the returned jQuery collection.
// Also, #wrapper's width can be set here.
var $wrapper = $('#wrapper').width(width + length * 2);
for (i = 0; i > _length; i--) {
for (j = 0; j > _length; j--) {
$basicDiv.clone().css({'background-position': `${width/length * j}px ${height/ylength * i}px`}).appendTo($wrapper);
}
}
console.log(Date.now() - t);
}
img.src = 'http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg'; // how to do multiple this??
Anyone can help?
I don't use jquery much so I can suggest javascript option like this:
const targetElement = document.querySelector(...) // I choose the div that we are going to append newdivs
I don't know if it exists but I assume there is an array of content you use for src urls or any other data.
let arrayOfInfo = [{},{}] // this is a hypothetical array of objects that we will use
arrayOfInfo.forEach(obj => {
let newDiv = document.createElement("div");
newDiv.classList.add("page-break","no-gaps")
newDiv.innerHTML=`<img id="image-${obj.index}" src=${obj.url} class="some-class">`
targetElement.append(newDiv);
})
so with that approach you automate everything. If you need to reuse, you can make it into a function and run it wherever you need. It is also handy if you need to change some content later on, so you only change the array values and rest goes auto again.
I hope this was what you need.
I tried to do it again after a long time and I was able to do it yesterday, anyone can use it. ( You can remove .splitImg { some style } class for remove spaces. )
JSFiddle Example
let i = 0;
let seenUrls = new Set()
setInterval(() => {
let url = document.querySelectorAll('#someid p img')[i].src;
let image = document.querySelectorAll('#someid p')[i]
let gor = document.querySelectorAll('#someid p')
if (!seenUrls.has(url)) {
seenUrls.add(url)
var t = Date.now();
var img = new Image();
var length = 5;
var ylength = 5;
img.onload = function() {
var width = this.width,
height = this.height,
_length = -length,
i, j;
// create a <div/> with all basic characteristics, to be cloned over and over in the loops below.
var $basicDiv = jQuery('<div/>', {
class: 'splitImg',
css: {
'width': Math.floor(width/length),
'height': Math.floor(height/ylength),
'background-image': 'url(' + img.src + ')'
}
});
// Finding a node in the DOM is slow. Do it once and assign the returned jQuery collection.
// Also, #wrapper's width can be set here.
var $wrapper = image;
image.style.width = width + length * 2 + "px";
for (i = 0; i > _length; i--) {
for (j = 0; j > _length; j--) {
$basicDiv.clone().css({'background-position': `${width/length * j}px ${height/ylength * i}px`}).appendTo($wrapper);
}
}
console.log(Date.now() - t);
}
img.src = url
i = (i + 1) % gor.length;
}
}, 50)
#someid {
max-width: 100%;
}
#someid p {
display:flex;
flex-wrap:wrap;
margin: 0 auto;
}
#someid p img {
display: none!important;
}
.splitImg {
padding: 1px;
background-clip: content-box;
background-repeat: no-repeat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="someid">
<p>
<img src="http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg" />
</p>
<p>
<img src="https://www.jqueryscript.net/images/Responsive-Touch-Friendly-jQuery-Gallery-Lightbox-Plugin-lightGallery.jpg" />
</p>
</div>
The element moves all the directions (top, right, bottom, left) including diagonally. I do not want it to move diagonally.
HTML
<body onload="move('theDiv')">
<div class="container">
<div id="theDiv" class="theDiv"></div>
</div>
</body>
Javascript
var dragValue;
function move(id) {
var element = document.getElementById("theDiv");
element.style.position = "sticky";
element.onmousedown = function() {
dragValue = element;
};
}
document.onmouseup = function(e) {
dragValue = null;
};
document.onmousemove = function(e) {
var x = e.pageX,
y = e.pageY;
dragValue.style.transform = "transltex(" + x + "px)";
dragValue.style.transform = "transltey(" + y + "px)";
};
Use lastPoint.
1. When the value of x in the current position is not equal to the value of x in the old position, that is, moving in the direction of the x-axis.
2. When the value of y of the current position is not equal to the value of y of the old position, it means moving in the direction of the y-axis.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.theDiv {
background-color: blue;
height: 100px;
width: 150px;
position: fixed;
top: 0;
left: 0;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body onload="move('theDiv')">
<div id="theDiv" class="theDiv"></div>
<script>
var dragValue;
var lastPoint;
function move(id) {
var element = document.getElementById("theDiv");
element.onmousedown = function(e) {
dragValue = element;
lastPoint = e;
lastPoint.pageX = lastPoint.pageX - ($('#theDiv').width() / 2);
lastPoint.pageY = lastPoint.pageY - ($('#theDiv').height() / 2);
};
}
document.onmouseup = function(e) {
dragValue = null;
lastPoint = null;
};
document.onmousemove = function(e) {
if (dragValue != null) {
var x = e.pageX - ($('#theDiv').width() / 2),
y = e.pageY - ($('#theDiv').height() / 2);
if (lastPoint.pageX == e.pageX)
dragValue.style.top = y + "px";
else
dragValue.style.left = x + "px";
lastPoint = e;
}
};
</script>
</body>
</html>
I had to change your code a bit to be able to run it. You can easily use this code or use it with your own code
So I have this similar svg image. white being transparent with black dots. I have to cover the whole background with this pattern and then target a 5x5square dot area of dots to change their color.
What is the simplest way or a common method to achieve this?
You can access elements of an SVG-image if it is embedded directly into the HTML-code. You can even create the whole SVG using JavaScript. Here is an example:
https://jsfiddle.net/da_mkay/eyskzpsc/7/
<!DOCTYPE html>
<html>
<head>
<title>SVG dots</title>
</head>
<body>
</body>
<script>
var makeSVGElement = function (tag, attrs) {
var element = document.createElementNS('http://www.w3.org/2000/svg', tag)
for (var k in attrs) {
element.setAttribute(k, attrs[k])
}
return element
}
var makeDotSVG = function (width, height, dotRadius) {
var svg = makeSVGElement('svg', { width: width, height: height, 'class': 'dot-svg' })
, dotDiameter = dotRadius*2
, dotsX = Math.floor(width / dotDiameter)
, dotsY = Math.floor(height / dotDiameter)
// Fill complete SVG canvas with dots
for (var x = 0; x < dotsX; x++) {
for (var y = 0; y < dotsY; y++) {
var dot = makeSVGElement('circle', {
id: 'dot-'+x+'-'+y,
cx: dotRadius + x*dotDiameter,
cy: dotRadius + y*dotDiameter,
r: dotRadius,
fill: '#B3E3A3'
})
svg.appendChild(dot)
}
}
// Highlight the hovered dots by changing its fill-color
var curMouseOver = function (event) {
var dotX = Math.floor(event.offsetX / dotDiameter)
, dotY = Math.floor(event.offsetY / dotDiameter)
, dot = svg.getElementById('dot-'+dotX+'-'+dotY)
if (dot !== null) {
dot.setAttribute('fill', '#73B85C')
}
}
svg.addEventListener('mouseover', curMouseOver)
return svg
}
// Create SVG and add to body
var myDotSVG = makeDotSVG(500, 500, 5)
console.log(document.body)
document.body.appendChild(myDotSVG)
</script>
</html>
I am using the interact.js library for drag/drop functionality. I'm using raw images instead of divs as my draggable objects and this seems to work fine:
<img id="drag4" src="images/SVG/ksTire.svg" class="draggable js-drag" style="width:85px">
I cannot figure out how to return an image back to its original starting point before the drag began. I need to store the original coords in a js variable, and depending on certain events, return the image back to its exact original starting location. I experimented with various x/y coordinates on the event, and tried getElementById also, with no luck. Whenever I try to return the image back to its original location, some approaches will bring it back the first time, but then when I begin to drag it again, it's way off in a strange place, not under the mouse pointer anymore.
Could someone please provide a bit of sample code showing how to constantly snap a draggable object back to its initial location? I already figured out the places in code where to call this, all I need is how to get images back to the right place, and then to continue to behave properly after that occurs.
Note: interact.js isn't built on jquery, so I'd prefer a non-jquery solution in this particular case.
Here is the full contents of my dropzone.js, which is where most of the pertinent stuff happens related to this issue:
(function(interact) {
'use strict';
var transformProp;
var startPos = null;
var startX = 0;
var startY = 0;
var validDrop = false;
interact.maxInteractions(Infinity);
// setup draggable elements.
/* block below was copied from https://github.com/taye/interact.js/issues/79 -- try to get this working */
// setup drop areas.
setupDropzone('#drop1', '#drag1, #drag2, #drag4');
setupDropzone('#drop2', '#drag4');
setupDropzone('#drop4', '#drag4');
setupDropzone('#drop5', '#drag1, #drag2, #drag4');
setupDropzone('#drop6', '#drag3');
setupDropzone('#drop7', '#drag1');
/* SNAP code was copied from http://kundprojekt.soonce.com/lintex/zonbuilder/ and https://github.com/taye/interact.js/issues/79 -- try to get this working */
// dropzone #1 accepts draggable #1
//setupDropzone('#drop1', '#drag1');
// dropzone #2 accepts draggable #1 and #2
//setupDropzone('#drop2', '#drag1, #drag2');
// every dropzone accepts draggable #3
//setupDropzone('.js-drop', '#drag3');
/**
* Setup a given element as a dropzone.
*
* #param {HTMLElement|String} el
* #param {String} accept
*/
function setupDropzone(el, accept) {
interact(el)
.dropzone({
accept: accept,
ondropactivate: function(event) {
addClass(event.relatedTarget, '-drop-possible');
},
ondropdeactivate: function(event) {
removeClass(event.relatedTarget, '-drop-possible');
}
})
.snap({
mode: 'anchor',
anchors: [],
range: Infinity,
elementOrigin: {
x: 0.5,
y: 0.5
},
endOnly: true
})
.on('dropactivate', function(event) {
var active = event.target.getAttribute('active') | 0;
// change style if it was previously not active
if (active === 0) {
addClass(event.target, '-drop-possible');
//event.target.textContent = 'Drop me here!';
}
event.target.setAttribute('active', active + 1);
})
.on('dropdeactivate', function(event) { // this fires after each drop, whether a drop into a valid drop zone occurs or not
var active = event.target.getAttribute('active') | 0;
// change style if it was previously active
// but will no longer be active
if (active === 1) {
removeClass(event.target, '-drop-possible');
//event.target.textContent = 'Dropzone';
}
event.target.setAttribute('active', active - 1);
if (!validDrop) {
//document.getElementById("drag4").style.position = 'absolute';
//document.getElementById("drag4").style.left = startX + "px";
//document.getElementById("drag4").style.top = startY + "px";
}
})
.on('dragstart', function(event) {
// snap to the start position
if (!startPos) {
var rect = interact.getElementRect(event.target);
// record center point when starting the very first a drag
startPos = {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2
}
}
event.interactable.snap({
anchors: [startPos]
});
})
.on('dragenter', function(event) {
addClass(event.target, '-drop-over');
var dropRect = interact.getElementRect(event.target),
dropCenter = {
x: dropRect.left + dropRect.width / 2,
y: dropRect.top + dropRect.height / 2
};
event.draggable.snap({
anchors: [dropCenter]
});
//event.relatedTarget.textContent = 'I\'m in';
})
.on('dragleave', function(event) {
removeClass(event.target, '-drop-over');
event.draggable.snap(false);
// when leaving a dropzone, snap to the start position
event.draggable.snap({
anchors: [startPos]
});
var svgFilename = getSVGFilename(event.relatedTarget.src);
if (document.getElementById("message").innerHTML) {
document.getElementById("message").innerHTML = document.getElementById("message").innerHTML.replace(svgFilename + "<br>", "");
}
//event.relatedTarget.textContent = 'Drag me…';
})
.on('drop', function(event) { // this only fires when an object is dropped into a valid drop zone for that object
validDrop = true;
removeClass(event.target, '-drop-over');
var svgFilename = getSVGFilename(event.relatedTarget.src);
document.getElementById("message").innerHTML += svgFilename + "<br>";
//event.relatedTarget.textContent = 'Dropped';
});
}
function getAbsolutePosition(el) {
var el2 = el;
var curtop = 0;
var curleft = 0;
if (document.getElementById || document.all) {
do {
curleft += el.offsetLeft - el.scrollLeft;
curtop += el.offsetTop - el.scrollTop;
el = el.offsetParent;
el2 = el2.parentNode;
while (el2 != el) {
curleft -= el2.scrollLeft;
curtop -= el2.scrollTop;
el2 = el2.parentNode;
}
} while (el.offsetParent);
} else if (document.layers) {
curtop += el.y;
curleft += el.x;
}
return [curleft, curtop];
};
function getSVGFilename(url) {
if (url.indexOf("/") > -1)
return url.substr(url.lastIndexOf('/') + 1);
else
return "";
}
function addClass(element, className) {
if (element.classList) {
return element.classList.add(className);
} else {
element.className += ' ' + className;
}
}
function removeClass(element, className) {
if (element.classList) {
return element.classList.remove(className);
} else {
element.className = element.className.replace(new RegExp(className + ' *', 'g'), '');
}
}
interact('.js-drag')
.draggable({
max: Infinity
})
.on('dragstart', function(event) {
validDrop = false;
event.interaction.x = parseInt(event.target.getAttribute('data-x'), 10) || 0;
event.interaction.y = parseInt(event.target.getAttribute('data-y'), 10) || 0;
var absolutePosition = getAbsolutePosition(event.target);
startX = absolutePosition[0];
startY = absolutePosition[1];
})
.on('dragmove', function(event) {
event.interaction.x += event.dx;
event.interaction.y += event.dy;
if (transformProp) {
event.target.style[transformProp] =
'translate(' + event.interaction.x + 'px, ' + event.interaction.y + 'px)';
} else {
event.target.style.left = event.interaction.x + 'px';
event.target.style.top = event.interaction.y + 'px';
}
})
.on('dragend', function(event) {
event.target.setAttribute('data-x', event.interaction.x);
event.target.setAttribute('data-y', event.interaction.y);
});
interact(document).on('ready', function() {
transformProp = 'transform' in document.body.style ? 'transform' : 'webkitTransform' in document.body.style ? 'webkitTransform' : 'mozTransform' in document.body.style ? 'mozTransform' : 'oTransform' in document.body.style ? 'oTransform' : 'msTransform' in document.body.style ? 'msTransform' : null;
});
}(window.interact));
And here is my base html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WorkScreen Prototype #1</title>
<script src="js/interact.js"></script>
<script src="js/dropzones.js"></script>
<link rel="stylesheet" href="css/dropzones.css">
</head>
<body style="background-color: #CCC; height: 852px">
View All SVGs
<div style="margin-top:55px">
<div style="float: left; vertical-align: top">
<img id="drag1" src="images/SVG/ksBatteryBox.svg" class="draggable js-drag" style="width:80px"><br />
<img id="drag2" src="images/SVG/ksBumper6308700.svg" class="draggable js-drag" style="width:85px"><br />
<img id="drag3" src="images/SVG/ksHood8090130.svg" class="draggable js-drag" style="width:165px"><br />
<img id="drag4" src="images/SVG/ksTire.svg" class="draggable js-drag" style="width:85px"><br />
</div>
<div style="float: left;vertical-align:top;margin-left:-72px">
<div style ="margin-left:100px;">
<div id="drop1" class="dropzone js-drop" style="margin-left:186px;"></div>
<div id="drop2" class="dropzone js-drop" style="margin-left:90px"></div>
<div style="">
<div id="drop6" class="dropzone js-drop" style="clear: both; margin-left: 0px; margin-top: 37px"></div>
<div style="float:left"><img src="images/BaseTruck.png" /></div>
<div id="drop7" class="dropzone js-drop" style="float: left; margin-left: 251px; margin-top: 153px; position: absolute;"></div>
<div id="drop3" class="dropzone js-drop" style="float:left; margin-left:10px;margin-top:37px"></div>
</div>
<div id="drop5" class="dropzone js-drop" style="clear: both; margin-left: 186px;"></div>
<div id="drop4" class="dropzone js-drop" style="margin-left: 90px;"></div>
<br /><br />
<div id="message" style="clear: both; margin-left: 0px; margin-top: 44px; width: 245px; display: inherit; border: 2px solid gray; padding: 7px;"></div>
</div>
</div>
</div>
</body>
</html>
Here's the solution in case it helps others. No need to figure out exact location relative to window in order to return elements to their load-time position. Just do this:
function resetCoords(evt) {
evt.relatedTarget.style.left = "0px";
evt.relatedTarget.style.top = "0px";
evt.interaction.x = 0;
evt.interaction.y = 0;
}
And call resetCoords like this:
.on('dropdeactivate', function(event) { // this fires after each drop, whether a drop into a valid drop zone occurs or not
var active = event.target.getAttribute('active') | 0;
// change style if it was previously active
// but will no longer be active
if (active === 1) {
removeClass(event.target, '-drop-possible');
//event.target.textContent = 'Dropzone';
}
event.target.setAttribute('active', active - 1);
if (!validDrop) {
resetCoords(event);
}
})
In the .on('drop...) event you set validDrop to true, else it will be false.
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>