Connecting images with lines - javascript

I tried to make match two pairs with lines quiz. I have couple of images on left, and couple of images on right, and I need to connect it with lines when you click on pair of images. It should work for any combinantion, so if I click for example on image 1 on left and image 3 on right, they should be connected with line. Then if I click again on image 1 on right, and image 2 on left, previous line should be deleted, and the new one between those two images need to be made.
Html snippet:
function lineDistance(x, y, x0, y0){
return Math.sqrt((x -= x0) * x + (y -= y0) * y);
};
function drawLine(a, b, line) {
var pointA = $(a ).offset();
var pointB = $(b).offset();
var pointAcenterX = $(a).width() / 2;
var pointAcenterY = $(a).height() / 2;
var pointBcenterX = $(b).width() / 2;
var pointBcenterY = $(b).height() / 2;
var angle = Math.atan2(pointB.top - pointA.top, pointB.left - pointA.left) * 180 / Math.PI;
var distance = lineDistance(pointA.left, pointA.top, pointB.left, pointB.top);
// Set Angle
$(line).css('transform', 'rotate(' + angle + 'deg)');
// Set Width
$(line).css('width', distance + 'px');
// Set Position
$(line).css('position', 'absolute');
if(pointB.left < pointA.left) {
$(line).offset({top: pointA.top + pointAcenterY, left: pointB.left + pointBcenterX});
} else {
$(line).offset({top: pointA.top + pointAcenterY, left: pointA.left + pointAcenterX});
}
}
new drawLine('.a', '.b', '.line');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question">
<div id="old" class="left_side one_half svg left">
<img class="a" src="assets/svg/Kerze.svg">
<img src="assets/svg/Telefon.svg">
<img src="assets/svg/Schreibmaschine.svg">
<img src="assets/svg/TV_old.svg">
<img src="assets/svg/Zeitstopper.svg">
<img src="assets/svg/Besen.svg">
<img src="assets/svg/Waschen.svg">
</div>
<div class="left_side one_half svg right">
<img src="assets/svg/Iwatch.svg">
<img src="assets/svg/Laptop.svg">
<img src="assets/svg/Staubsauger.svg">
<img src="assets/svg/Waschmaschine.svg">
<img src="assets/svg/TV_new.svg">
<img src="assets/svg/Gluehbirne.svg">
<img class="b" src="assets/svg/Iphone.svg">
<div class="line"></div>
</div>
</div>
I manage to make a line between two images (from class a to class b), and it is always calculated to be exactly on right angle, but I can not make it appear to work as I described above. Any ideas? Thanks.

var setLeft = false, setRight = false;
$('.leftSide img').click(function(){
$('.leftSide img').removeClass('a');
$(this).addClass('a');
setLeft = true;
new drawLine('.a', '.b', '.line');
});
$('.rightSide img').click(function(){
$('.rightSide img').removeClass('b');
$(this).addClass('b');
setRight = true;
new drawLine('.a', '.b', '.line');
});
You can use a flag variables and when click on an image from the right, set the right flag variable to be true and do the same with the other.
Then inside your function drawLine just check if the two flags are true then draw the line between a and b and set the two flag variables to false.
function lineDistance(x, y, x0, y0){
return Math.sqrt((x -= x0) * x + (y -= y0) * y);
};
function drawLine(a, b, line) {
if(setLeft && setRight){
setLeft = false;
setRight = false;
var pointA = $(a).offset();
var pointB = $(b).offset();
console.log(pointA);
console.log(pointB);
var pointAcenterX = $(a).width() / 2;
var pointAcenterY = $(a).height() / 2;
var pointBcenterX = $(b).width() / 2;
var pointBcenterY = $(b).height() / 2;
var angle = Math.atan2(pointB.top - pointA.top, pointB.left - pointA.left) * 180 / Math.PI;
var distance = lineDistance(pointA.left, pointA.top, pointB.left, pointB.top);
// Set Angle
$(line).css('transform', 'rotate(' + angle + 'deg)');
// Set Width
$(line).css('width', distance + 'px');
// Set Position
$(line).css('position', 'absolute');
if(pointB.left < pointA.left) {
$(line).offset({top: pointA.top + pointAcenterY, left: pointB.left + pointBcenterX});
} else {
$(line).offset({top: pointA.top + pointAcenterY, left: pointA.left + pointAcenterX});
}
}
}
//new drawLine('.a', '.b', '.line');
var setLeft = false, setRight = false;
$('.leftSide img').click(function(){
$('.leftSide img').removeClass('a');
$(this).addClass('a');
setLeft = true;
new drawLine('.a', '.b', '.line');
});
$('.rightSide img').click(function(){
$('.rightSide img').removeClass('b');
$(this).addClass('b');
setRight = true;
new drawLine('.a', '.b', '.line');
});
.left{
float:left;
}
.right{
float:right;
}
.one_half{
width:40%;
}
img{
max-width:100%;
}
.line{
background: red;
height:1px;
}
.question{
position: relative;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question">
<div id="old" class="left_side one_half svg left leftSide">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
</div>
<div class="left_side one_half svg right rightSide">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<img src="https://www.w3schools.com/css/trolltunga.jpg">
<div class="line"></div>
</div>
</div>

Related

zoom in zoom out image on scrolling in javascript

I created tabs with image.When I scroll on the image it will zoom in and zoom out. But I am facing the problem,in only first tab it is working with function zoom in & zoom out(when i scroll).I didn't get what i'm doing wrong.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>zoom</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
ul li{
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
</ul>
</span>
</div>
<div class="panel-body">
<br />
<br />
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="container">
<div class="slide">
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab2">
<div class="container">
<div class="slide">
<img class='zoom' src='abc.jpg' alt='abc' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab3">
<div class="container">
<div class="slide">
<img class='zoom' src='xy.jpg' alt='xy' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab4">
<div class="container">
<div class="slide">
<img class='zoom' src='rec.png' alt='rec' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- <img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
<br />
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/> -->
<script src="wheelzoom.js"></script>
<script>
wheelzoom(document.querySelector('img.zoom'));
</script>
</body>
</html>
wheelzoom.js
window.wheelzoom = (function(){
var defaults = {
zoom: 0.10,
maxZoom: false,
initialZoom: 1,
};
var main = function(img, options){
if (!img || !img.nodeName || img.nodeName !== 'IMG') { return; }
var settings = {};
var width;
var height;
var bgWidth;
var bgHeight;
var bgPosX;
var bgPosY;
var previousEvent;
var cachedDataUrl;
function setSrcToBackground(img) {
img.style.backgroundRepeat = 'no-repeat';
img.style.backgroundImage = 'url("'+img.src+'")';
cachedDataUrl = 'data:image/svg+xml;base64,'+window.btoa('<svg xmlns="http://www.w3.org/2000/svg" width="'+img.naturalWidth+'" height="'+img.naturalHeight+'"></svg>');
img.src = cachedDataUrl;
}
function updateBgStyle() {
if (bgPosX > 0) {
bgPosX = 0;
} else if (bgPosX < width - bgWidth) {
bgPosX = width - bgWidth;
}
if (bgPosY > 0) {
bgPosY = 0;
} else if (bgPosY < height - bgHeight) {
bgPosY = height - bgHeight;
}
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
}
function reset() {
bgWidth = width;
bgHeight = height;
bgPosX = bgPosY = 0;
updateBgStyle();
}
function onwheel(e) {
var deltaY = 0;
e.preventDefault();
if (e.deltaY) { // FireFox 17+ (IE9+, Chrome 31+?)
deltaY = e.deltaY;
} else if (e.wheelDelta) {
deltaY = -e.wheelDelta;
}
// As far as I know, there is no good cross-browser way to get the cursor position relative to the event target.
// We have to calculate the target element's position relative to the document, and subtrack that from the
// cursor's position relative to the document.
var rect = img.getBoundingClientRect();
var offsetX = e.pageX - rect.left - window.pageXOffset;
var offsetY = e.pageY - rect.top - window.pageYOffset;
// Record the offset between the bg edge and cursor:
var bgCursorX = offsetX - bgPosX;
var bgCursorY = offsetY - bgPosY;
// Use the previous offset to get the percent offset between the bg edge and cursor:
var bgRatioX = bgCursorX/bgWidth;
var bgRatioY = bgCursorY/bgHeight;
// Update the bg size:
if (deltaY < 0) {
bgWidth += bgWidth*settings.zoom;
bgHeight += bgHeight*settings.zoom;
} else {
bgWidth -= bgWidth*settings.zoom;
bgHeight -= bgHeight*settings.zoom;
}
if (settings.maxZoom) {
bgWidth = Math.min(width*settings.maxZoom, bgWidth);
bgHeight = Math.min(height*settings.maxZoom, bgHeight);
}
// Take the percent offset and apply it to the new size:
bgPosX = offsetX - (bgWidth * bgRatioX);
bgPosY = offsetY - (bgHeight * bgRatioY);
// Prevent zooming out beyond the starting size
if (bgWidth <= width || bgHeight <= height) {
reset();
} else {
updateBgStyle();
}
}
function drag(e) {
e.preventDefault();
bgPosX += (e.pageX - previousEvent.pageX);
bgPosY += (e.pageY - previousEvent.pageY);
previousEvent = e;
updateBgStyle();
}
function removeDrag() {
document.removeEventListener('mouseup', removeDrag);
document.removeEventListener('mousemove', drag);
}
// Make the background draggable
function draggable(e) {
e.preventDefault();
previousEvent = e;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', removeDrag);
}
function load() {
var initial = Math.max(settings.initialZoom, 1);
if (img.src === cachedDataUrl) return;
var computedStyle = window.getComputedStyle(img, null);
width = parseInt(computedStyle.width, 10);
height = parseInt(computedStyle.height, 10);
bgWidth = width * initial;
bgHeight = height * initial;
bgPosX = -(bgWidth - width)/2;
bgPosY = -(bgHeight - height)/2;;
setSrcToBackground(img);
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
img.addEventListener('wheelzoom.reset', reset);
img.addEventListener('wheel', onwheel);
img.addEventListener('mousedown', draggable);
}
var destroy = function (originalProperties) {
img.removeEventListener('wheelzoom.destroy', destroy);
img.removeEventListener('wheelzoom.reset', reset);
img.removeEventListener('load', load);
img.removeEventListener('mouseup', removeDrag);
img.removeEventListener('mousemove', drag);
img.removeEventListener('mousedown', draggable);
img.removeEventListener('wheel', onwheel);
img.style.backgroundImage = originalProperties.backgroundImage;
img.style.backgroundRepeat = originalProperties.backgroundRepeat;
img.src = originalProperties.src;
}.bind(null, {
backgroundImage: img.style.backgroundImage,
backgroundRepeat: img.style.backgroundRepeat,
src: img.src
});
img.addEventListener('wheelzoom.destroy', destroy);
options = options || {};
Object.keys(defaults).forEach(function(key){
settings[key] = options[key] !== undefined ? options[key] : defaults[key];
});
if (img.complete) {
load();
}
img.addEventListener('load', load);
};
// Do nothing in IE9 or below
if (typeof window.btoa !== 'function') {
return function(elements) {
return elements;
};
} else {
return function(elements, options) {
if (elements && elements.length) {
Array.prototype.forEach.call(elements, main, options);
} else if (elements && elements.nodeName) {
main(elements, options);
}
return elements;
};
}
}());
When i scroll it is zoom in and zoom out but only in first tab.What I did wrong,i can't understand.Please help me.Thank you.
Nice work i worked it out and find that you are using wheelzoom(document.querySelector('img.zoom')); here in this code you are using querySelector where this code will return only one element not all element instead of this code you need to use wheelzoom(document.querySelectorAll('img.zoom')); then your example will work . I have tried and its working

JavaScript 3d Viewer using images with Rotation and Zoom

I am trying to develop interactive 3d viewer with Rotation and Zoom using Java script. I successfully developed a script to view product which rotates only in one axis(X-axis), but need script sample to view product which is taken in X,Y and Z axis. I have attached an image which shows camera placements.
Fig-1 Sample Camera placement
Fig -1 Shows camera positions where images are taken in single axis, This is achieved and below is the code.
<html>
<head>
<style type="text/css">
table img {
height: 250px;
width: 250px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var arr = new Array();
var xCurrent = 0;
var currentImgPos = 0;
$("#dvImages img").each(function () {
arr.push($(this).attr("src"));
});
$("#product").attr("src", arr[0]);
$("#product").mouseleave(function () { xCurrent = 0; });
$("#product").mousemove(function (e) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
if (xCurrent > relX) {
if (relX - xCurrent <= -5) {
if (currentImgPos >= 25) {
currentImgPos = 0;
$("#product").attr("src", arr[currentImgPos]);
}
else {
currentImgPos = currentImgPos + 1;
$("#product").attr("src", arr[currentImgPos]);
}
xCurrent = relX;
}
}
else {
if (relX - xCurrent >= 5) {
if (currentImgPos <= 0) {
currentImgPos = 25;
$("#product").attr("src", arr[currentImgPos]);
}
else {
currentImgPos = currentImgPos - 1;
$("#product").attr("src", arr[currentImgPos]);
}
xCurrent = relX;
}
}
});
});
</script>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<img alt="" src="" id="product" />
</td>
</tr>
</table>
<div id="dvImages" style="display: none">
<img alt="" src="http://www.mathieusavard.info/threesixty/1.jpg" />
<img alt="" src="http://www.mathieusavard.info/threesixty/5.jpg" />
<img alt="" src="http://www.mathieusavard.info/threesixty/9.jpg" />
<img alt="" src="http://www.mathieusavard.info/threesixty/13.jpg" />
<img alt="" src="http://www.mathieusavard.info/threesixty/17.jpg" />
<img alt="" src="http://www.mathieusavard.info/threesixty/21.jpg" />
<img alt="" src="http://www.mathieusavard.info/threesixty/25.jpg" />
</div>
</body>
</html>
Fig-2 New Camera placement
Fig -2 Shows camera positions where images are taken in X,Y and Z axis. Need sample code this part

Increase and decrease value in Pure Javascript

I'm trying to develop a very simple carousel with Pure Javascript and CSS. I'm having trouble with the "next" and "previous" button, since they should communicate the with each other, setting the current position of the carousel.
Here is my current code (or JsFiddle: https://jsfiddle.net/kbumjLw2/1/):
// Slider
var listRecommendations = document.getElementById('list-recommendations');
listRecommendations.style.left = 0;
// Previous button
document.getElementById("btn-prev").onclick = function() {
// Making sure this functions will not run if it's the 0px of the slider
if (parseInt(listRecommendations.style.left) != 0) {
var currentPosition = parseInt(listRecommendations.style.left) + 100;
listRecommendations.style.left = currentPosition + 'px';
console.log(currentPosition);
};
}
// Next button
var num = 100;
var maxValue = 1000 + 120;
console.log(maxValue);
document.getElementById("btn-next").onclick = function() {
if (num < maxValue) {
num += 100;
listRecommendations.style.left = '-' + num + 'px';
console.log(num);
};
}
#list-recomendations{
position: absolute;
}
.wrap-items .item{
float: left;
}
<div class="recommendation">
<div id="slider">
<div id="list-recommendations" class="wrap-items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
</div>
<!-- Slider controls -->
<button id="btn-prev" class="btn-slider prev">Previous</button>
<button id="btn-next" class="btn-slider next" title="Ver mais sugestões">Next</button>
</div>
As you can see on the console, the next button increases "100" at each click, and the previous button decreases "100" at each click. The previous button seems to be working fine, but the next button don't get the updated value, it always increase using the latest value it used.
Expected result:
Next button clicked: 100 > 200 > 300...
Prev button clicked: 200 > 100 > 0...
Next button clicked: 100 > 200 > 300...
Current result:
Next button clicked: 100 > 200 > 300...
Prev button clicked: 200 > 100 > 0...
Next button clicked: 400 > 500 > 600...
Any idea on what may be causing this issue?
check this updated fiddle
// Previous button
document.getElementById("btn-prev").onclick = function() {
// Making sure this functions will not run if it's the 0px of the slider
var currentPosition = parseInt(listRecommendations.style.left) - 100;
listRecommendations.style.left = currentPosition + 'px';
console.log(currentPosition);
}
// Next button
var num = 100;
var maxValue = 1000 + 120;
console.log(maxValue);
document.getElementById("btn-next").onclick = function() {
if (num < maxValue) {
var currentPosition = parseInt(listRecommendations.style.left) + 100;
num = currentPosition;
listRecommendations.style.left = num + 'px';
console.log(num);
};
}
you basically need to take the left value each time and do plus (+ next) minus (- prev) on it.
There is no use of num as you can play with the current position of the element.
Also note, - will concatenate the - symbol the the value, it will not subtract the value.
Ty this:
var maxValue = 1000 + 120;
var listRecommendations = document.getElementById('list-recommendations');
listRecommendations.style.left = 0;
document.getElementById("btn-prev").onclick = function() {
var val = parseInt(listRecommendations.style.left);
if (val != 0) {
val -= 100;
listRecommendations.style.left = val + 'px';
console.log(val);
};
}
document.getElementById("btn-next").onclick = function() {
var val = parseInt(listRecommendations.style.left);
if (val < maxValue) {
val += 100;
listRecommendations.style.left = val + 'px';
console.log(val);
};
}
#list-recomendations {
position: absolute;
}
.wrap-items .item {
float: left;
}
<div class="recommendation">
<div id="slider">
<div id="list-recommendations" class="wrap-items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
</div>
<!-- Slider controls -->
<button id="btn-prev" class="btn-slider prev">Previous</button>
<button id="btn-next" class="btn-slider next" title="Ver mais sugestões">Next</button>
</div>
Fiddle here

How to move one image randomly when you click on the other image using html & javascript

I am a beginner with javascript. I have two images. One is for clicking, and the other one is for moving 10px to the left & right randomly. Once I click on the "high5" image, "pic2" image has to move randomly in any direction no more than 10 pixels. Every click is added to the score to generate total score at the end. I am stuck at this point, and I don't know where to go. Can someone help me, please?
As you can see, I have edited my code. I'm still having problems in:
Creating scoreboard to keep track of how many clicks the user
clicked within 30 seconds.
I need a timer that counts 30 seconds.
Every time the picture in the middle moves, it keep going to the
left.
HTML code:
<!DOCTYPE html>
<!-- game.html
Uses game.js
Illustrates visibility control of elements
-->
<html lang="en">
<head>
<title>Visibility control</title>
<meta charset="utf-8" />
</head>
<body>
<div id="score">
0
</div>
<div id="high5" style="position: relative; left: 10px;">
<img onclick= "moveImg(); clicked();" src="pics/high5.jpg"
style="height:250px; width:250px; " alt="Minion High Five" />
</div>
<div id="pic2" style="position: relative; top: 20px; left: 650px;">
<img src="pics/pic2.gif" style="height:250px; width:350px;"/>
</div>
<script type="text/javascript" src="game.js" ></script>
</body>
</html>
javascript:
var x = 0;
var y = 0;
var timer = 30;
var count = 0;
var isDone = true;
function moveImg() {
x += Math.floor(Math.random() * 20) - 10;
y += Math.floor(Math.random() * 20) - 10;
pic2.style.left = x + "px";
pic2.style.top = y + "px";
if(timer > 0) {
setTimeout("moveImg()", 50);
timer--;
}
else {
timer = 30;
}
}
function clicked() {
timer = 30;
count++;
score.innerHTML = count;
}
Try something like this: DO not use onclick inside HTML.I have added some jquery part,if you don't need change it accordingly or let me know.
var high5,myVar;
$(function(){
$("img").on("click",function(){
console.log($(this));
if($(this).data('id') == "minion"){
high5=document.getElementById('pic2');
high5.style.left="10px";
moveImg();
}
});
setInterval(function(){ myStopFunction(); }, 3000);//call to stop shacking after 3000 miliseconds.
});
function moveImg() {
//alert("hi");
var x;
x = Math.floor(Math.random()*4)+1;
left = parseInt(high5.style.left.replace('px', ''));
console.log(x+ "," +left);
if (x==4 && left >= 10) {
high5.style.left = (left - 10) + 'px';;
}
if (x==3 && left <= 650) {
high5.style.left = (left + 10) + 'px';
}
if (x==2 && left >= 10) {
high5.style.left = (left - 10) + 'px';;
}
if (x==1 && left <= 450) {
high5.style.left = (left + 10) + 'px';
}
myVar = setTimeout(function(){moveImg();},100);
}
function myStopFunction() {
clearTimeout(myVar);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "high5" style = "position: absolute;">
<img src="pics/high5.jpg" style="height:250px; width:250px;
margin-top: 50px; margin-left: 50px; border:none;"
alt="Minion High Five" data-id="minion"/>
</div>
<div id = "pic2" style=" position: absolute; width:350px;height:250px;margin-left: 550px;border:1px solid black;margin-top:150px;">
<img src="pics/pic2.gif" style="width:350px;height:250px;" alt="Minion High Five"/>
</div>

Check if draggable Object is in correct droppable container

I have items, which I can drag and drop around. Now, after I dropped the Item, I want to check if my object is in the correct container.
What would be the best way to achieve this?
This here is my function for it:
$(function () {
$("#draggable").draggable();
$(".item").droppable({
drop: function (event, ui) {
var $this = $(this);
$this.append(ui.draggable);
var draggableWidth = $('#draggable').width();
var draggableHeight = $('#draggable').height();
var width = $this.width();
var height = $this.height();
var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
var cntrTop = (height / 2) - (ui.draggable.height() / 2);
ui.draggable.animate({width: draggableWidth * 1.1, height: draggableHeight * 1.1});
ui.draggable.animate({width: draggableWidth, height: draggableHeight});
ui.draggable.css({
left: cntrLeft + "px",
top: cntrTop + "px"
});
// this here is still hard-coded, but it should trigger on the element I'm holding (image)
console.log($('#draggable4').data('image'));
console.log($(this).data('target'));
}
});
});
If you take a look at this example: JSFiddle you can see, what I'm actually stuck with. You can move the yellow square in the boxes, but there is no feedback if it is the correct one.
To clarify it a bit more: Lets say I have 2 squares, a yellow and a red one. If the yellow square is dropped on the left box, it should display an error. Otherwise a tick-symbol should appear (not that kind of a problem).
Same goes for the red one. If the red one is dropped in the right box, it should throw an error... you get the point.
Update 1:
My HTML
<div class="item" data-target="1"></div>
<div class="item2" data-target="2"></div>
<div class="item3" data-target="3"></div>
<div class="item4" data-target="4"></div>
<div style="position: relative; height: 100%;">
<img src="folie1/img1.png" width="153" height="124" id="draggable" style="z-index: 200;" data-image="1"/>
<img src="folie1/img2.png" width="153" height="124" id="draggable2" style="z-index: 201;" data-image="2"/>
<img src="folie1/img3.png" width="153" height="124" id="draggable3" style="z-index: 202;" data-image="3"/>
<img src="folie1/img4.png" width="153" height="124" id="draggable4" style="z-index: 203;" data-image="4"/>
</div>
I want to check if the current object (lets say data-image="1") is dropped in the container data-target="1".
Update 2
This is my HTML now:
<div class="item" id="item" data-target="1"></div>
<div class="item" id="item2" data-target="2"></div>
<div class="item" id="item3" data-target="3"></div>
<div class="item" id="item4" data-target="4"></div>
<div style="position: relative; height: 100%;">
<img src="folie1/img1.png" width="153" height="124" id="draggable" class="draggable"
style="z-index: 200;" data-image="1"/>
<img src="folie1/img2.png" width="153" height="124" id="draggable2" class="draggable"
style="z-index: 201;" data-image="2"/>
<img src="folie1/img3.png" width="153" height="124" id="draggable3" class="draggable"
style="z-index: 202;" data-image="3"/>
<img src="folie1/img4.png" width="153" height="124" id="draggable4" class="draggable"
style="z-index: 203;" data-image="4"/>
</div>
... with the JS from Rajen Ranjith
$(function () {
var result = {};
$(".draggable").draggable({
start: function (e) {
result.drag = e.target.id.split("_")[1];
}
});
$(".item").droppable({
drop: function (event, ui) {
var $this = $(this);
result.drop = event.target.id.split("_")[1];
if (result.drag == result.drop)
alert("true");
else
alert("false");
$this.append(ui.draggable);
var width = $this.width();
var height = $this.height();
var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
var cntrTop = (height / 2) - (ui.draggable.height() / 2);
ui.draggable.css({
left: cntrLeft + "px",
top: cntrTop + "px"
});
}
});
});
I can drag and drop my images, but it always alerts "true".
use id or attributes for both drag element and drop element
http://jsfiddle.net/rajen_ranjith/F3sD3/285/
$(function() {
var result = {};
$(".draggable").draggable({
start:function(e){
result.drag = e.target.id.split("_")[1];
}
});
$(".item").droppable({
drop: function(event, ui) {
var $this = $(this);
result.drop = event.target.id.split("_")[1];
if(result.drag == result.drop)
alert("true");
else
alert("false");
$this.append(ui.draggable);
var width = $this.width();
var height = $this.height();
var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
var cntrTop = (height / 2) - (ui.draggable.height() / 2);
ui.draggable.css({
left: cntrLeft + "px",
top: cntrTop + "px"
});
}
});
});
I've solved this by using the data-attribute in the dropable div, as described here. You can check the data-value with jQuery like this. The data-attribute could than be checked against a data-attribute on the draggable div. If equal, it could be the correct one.

Categories

Resources