Not able to display the image in the cropping area - javascript

Trying to display the image to the cropper. The image URL is there in the html src attribute but the image is not appearing.
When I click the edit button, I need to show the current image(The image which is above the edit button) in the cropper. So I can crop the part of the image i want. After cropping the image, if i click the update button, it should be updated. Please help me to complete.
window.onload = function() {
'use strict';
const noImage = 'https://via.placeholder.com/200x65';
var Cropper = window.Cropper;
var URL = window.URL || window.webkitURL;
var container = document.querySelector('.img-container');
var image = container.getElementsByTagName('img').item(0);
var cropBtn = document.querySelector('#crop-btn');
var rotate = document.querySelector('#rotate');
var resetImage = document.querySelector('#reset');
var zoomIn = document.querySelector('#zoomIn');
var zoomOut = document.querySelector('#zoomOut');
var deleteCofirmBtn = document.querySelector('#deleteCofirmBtn');
var profilePicture = document.querySelector('#profilePicture');
var deleteLinkContainer = document.querySelector('.deleteProfileImgWrap');
var modal = $('#modal');
var croppable = false;
var options = {
aspectRatio: 3 / 1,
viewMode: 1,
cropBoxResizable: false,
guides: false,
minContainerWidth: 300,
minContainerHeight: 200,
minCropBoxWidth: 200,
minCropBoxHeight: 65,
movable: true,
preview: '.img-preview',
ready: function() {
croppable = true;
},
};
var cropper = new Cropper(image, options);
var originalImageURL = image.src;
var uploadedImageType = 'image/jpeg';
var uploadedImageName = '';
var uploadedImageURL;
var inputImage = document.getElementById('editImage');
inputImage.addEventListener('click', function() {
const old_image = profilePicture;
image.src = old_image.src;
modal.modal({
backdrop: 'static'
});
cropper.destroy();
cropper = new Cropper(image, options);
console.log(`success`);
});
rotate.addEventListener('click', function() {
cropper.rotate(90);
});
reset.addEventListener('click', function() {
cropper.reset();
});
zoomOut.addEventListener('click', function() {
cropper.zoom(-0.1);
});
zoomIn.addEventListener('click', function() {
cropper.zoom(0.1);
});
deleteCofirmBtn.addEventListener('click', function() {
profilePicture.src = noImage;
$(".deleteProfileImgWrap").hide();
$('.file-upload-label').parent().fadeIn();
deleteLinkContainer.style.display = 'none';
});
cropBtn.addEventListener('click', function() {
let roundedCanvas;
let imgSrc = cropper.getCroppedCanvas({
width: 200,
height: 65
}).toDataURL();
deleteLinkContainer.style.display = 'block';
profilePicture.src = imgSrc;
});
}
#media(max-width: 767px) {
.profile-picture-wrap {
padding: 10px !important;
}
}
.profile-picture-wrap {
padding: 30px;
border: 1px solid #ccc;
border-radius: 4px;
}
.upload-button {
font-size: 1.2em;
}
.file-upload {
display: none !important;
}
.file-upload-label {
color: #007bfc;
font-weight: normal;
cursor: pointer;
}
#profilePicture {
cursor: pointer;
}
.file-upload-label:hover {
font-weight: bold;
}
.profile-pic {
cursor: pointer;
width: 200px;
height: 65px;
}
.profile-pic-wrap {
border: 1px solid #ccc;
padding: 30px 14px;
}
.my-profile-wrp p {
margin-bottom: 25px;
}
/* Cropper css */
.cropper-view-box,
.cropper-face {
border-radius: unset;
}
.profile-picture-wrap {
display: inline-block;
position: relative;
}
.profile-picture-wrap img {
border-radius: 0%;
}
.p-image {
position: unset;
}
.cropper-container {
margin-right: auto;
margin-left: auto;
}
.deleteProfileImgWrap {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.paperindex.com/bootstrap/css/font-awesome.min.css" rel="stylesheet">
<link href="https://cdn.paperindex.com/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css" rel="stylesheet">
<script src="https://cdn.paperindex.com/js/jquery/jquery-3.1.0.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js">
</script>
</head>
<body>
<div class="profile-picture-wrap">
<img id="profilePicture" src="https://cdn.paperindex.com/piimages/left-column/large-pool-of-suppliers.jpg" alt="Profile Picture">
<p id="editImage" class="text-center">Edit</p>
</div>
<p class="mrgn-top-4 deleteProfileImgWrap">Delete Photo
</p>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="mrgn-top-100"></div>
<!--topbar-header-wrap-->
</main>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal" type="button">×</button>
<h4 class="modal-title">Crop Your Photo</h4> <span></span>
</div>
<div class="modal-body">
<div class="img-container text-center">
<img id="image" src="" alt="Picture" style="width: 100%;max-height: 300px;">
<div class="mrgn-top-15">
<div class="btn-group">
<button id="zoomIn" type="button" class="btn btn-default"><i data-toggle="tooltip"
title="Zoom In" class="fa fa-search-plus" aria-hidden="true"></i></button>
<button id="zoomOut" type="button" class="btn btn-default"><i data-toggle="tooltip"
title="Zoom Out" class="fa fa-search-minus" aria-hidden="true"></i></button>
<button id="rotate" type="button" class="btn btn-default"><i data-toggle="tooltip"
title="Rotate" class="fa fa-repeat" aria-hidden="true"></i></button>
<button id="reset" type="button" class="btn btn-default"><i data-toggle="tooltip"
title="Reset" class="fa fa-refresh" aria-hidden="true"></i></button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="crop-btn" class="btn btn-default" data-dismiss="modal">Add
Photo</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<div class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal" type="button">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<!-- leftbox -->
<div class="box-2">
<div class="result"></div>
</div>
<!--rightbox-->
<div class="box-2 img-result hide">
<!-- result of crop -->
<img alt="" class="cropped" src="#"></div>
<!-- input file -->
<div class="box">
<div class="options hide">
<input class="img-w" type="hidden">
</div>
<!-- save btn -->
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" type="button">Cancel</button><button class="btn save hide" data-dismiss="modal">Update</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.paperindex.com/bootstrap/js/bootstrap.min.js">
</script>
<script src="https://cdn.paperindex.com/js/header/pi-header-functions.js">
</script>
</body>
</html>

function getRoundedCanvas(sourceCanvas) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
/* var width = sourceCanvas.width;
var height = sourceCanvas.height; */
var width = 100;
var height = 100;
canvas.width = width;
canvas.height = height;
context.imageSmoothingEnabled = true;
context.drawImage(sourceCanvas, 0, 0, width, height);
context.globalCompositeOperation = 'destination-in';
context.beginPath();
context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
context.fill();
return canvas;
}
window.addEventListener('DOMContentLoaded', function() {
var image = document.getElementById('image');
var button = document.getElementById('button');
var result = document.getElementById('result');
var croppable = false;
var cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 1,
minContainerWidth: 300,
minContainerHeight: 200,
minCropBoxWidth: 100,
minCropBoxHeight: 100,
ready: function() {
croppable = true;
},
});
button.onclick = function() {
var croppedCanvas;
var roundedCanvas;
var roundedImage;
if (!croppable) {
return;
}
// Crop
croppedCanvas = cropper.getCroppedCanvas();
// Round
roundedCanvas = getRoundedCanvas(croppedCanvas);
// Show
roundedImage = document.createElement('img');
roundedImage.src = roundedCanvas.toDataURL()
result.innerHTML = '';
result.appendChild(roundedImage);
};
});
img {
max-width: 100%;
}
.cropper-view-box,
.cropper-face {
border-radius: 50%;
}
.cropper-point.point-se {
height: 5px !important;
width: 5px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<link href="https://fengyuanchen.github.io/cropperjs/css/cropper.css" rel="stylesheet" />
<script src="https://fengyuanchen.github.io/cropperjs/js/cropper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet" />
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div id="result"></div>
Edit
</div>
</div>
</div>
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div>
<img id="image" src="https://fengyuanchen.github.io/cropperjs/images/picture.jpg" alt="Picture">
<!-- <img id="image" src="https://d1shuhu6tm6s0s.cloudfront.net/piimages/find-suppliers/Paper_Manufactures_PaperIndex_Map.png" alt="Picture">
</div> -->
</div>
<div class="modal-footer">
<button id="button" type="button" class="btn btn-success" data-dismiss="modal">Update</button>
</div>
</div>
</div>
</div>

Related

i dont know why when i change my operation variable inside the function when called into the event listener it doesnt change globally

i am new to javascript and i want to build a calculator but when i try to change the global variable operator in the event listener the operator variable changes only locally but when i need the variable in the event listener linked to equal button it takes the initial value of the operator which is empty so i cant choose the opertaor and do my calculations
let current_number = "";
let operator = "";
let previous = "";
let disp = document.querySelector("#current");
let prev = document.querySelector("#previous");
let equal = document.querySelector("#equal");
equal.addEventListener("click", calculate);
let number = document.querySelectorAll(".digit");
let oper = document.querySelectorAll(".operation");
number.forEach((element) => {
element.addEventListener("click", function(e) {
handleNumber(e.target.textContent);
disp.textContent = current_number;
});
});
oper.forEach((element) => {
element.addEventListener("click", (e) => {
handleOperator(e.target.textContent);
prev.textContent = previous + " " + operator;
disp.textContent = current_number;
});
});
function handleNumber(num) {
if (current_number.length < 10) {
current_number += num;
}
}
function handleOperator(op) {
operator = op;
previous = current_number;
current_number = "";
}
function calculate() {
previous = Number(previous);
current_number = Number(current_number);
if (operator === "+") {
previous += current_number;
} else if (operator === "-") {
previous -= current_number;
} else if (operator === "*") {
previous *= current_number;
} else {
previous /= current_number;
}
console.log(previous);
}
* {
box-sizing: border-box;
}
body {
padding: 0;
margin: 0;
background: linear-gradient(to right, #2a92c7, #00ffc6);
}
#container {
display: flex;
justify-content: center;
min-height: 100vh;
}
.btn {
border: 1px solid white;
border-radius: 0;
}
#main {
display: flex;
flex-direction: column;
align-items: flex-end;
justify-content: space-between;
height: 100px;
}
#current {
font-size: 2rem;
}
#display {
background-color: rgba(13, 42, 6, 0.7);
}
.btn:hover {
background-color: #9ea0a2;
}
.digit {
font: 900;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="styles.css" />
<script src="script.js" defer></script>
</head>
<body>
<div class="container-fluid">
<div
class="row text-light align-items-center justify-content-center"
style="min-height: 100vh"
>
<div id="display" class="col-sm-5 col-xl-4">
<div class="row">
<div id="main" class="col-12 bg-gradient">
<div id="previous" class="col"></div>
<div id="current" class="col"></div>
</div>
<button class="col-6 btn btn-secondary shadow-none">AC</button>
<button class="col-3 btn btn-secondary shadow-none">Del</button>
<button class="operation col-3 btn btn-secondary shadow-none">
/
</button>
<button class="digit col-3 btn btn-secondary shadow-none">1</button>
<button class="digit col-3 btn btn-secondary shadow-none">2</button>
<button class="digit col-3 btn btn-secondary shadow-none">3</button>
<button class="col-3 btn btn-secondary shadow-none operation">
*
</button>
<button class="digit col-3 btn btn-secondary shadow-none">4</button>
<button class="digit col-3 btn btn-secondary shadow-none">5</button>
<button class="digit col-3 btn btn-secondary shadow-none">6</button>
<button class="col-3 btn btn-secondary shadow-none operation">
-
</button>
<button class="digit col-3 btn btn-secondary shadow-none">7</button>
<button class="digit col-3 btn btn-secondary shadow-none">8</button>
<button class="digit col-3 btn btn-secondary shadow-none">9</button>
<button class="col-3 btn btn-secondary shadow-none operation">
+
</button>
<button
id="dicim"
class="digit col-3 btn btn-secondary shadow-none"
>
.
</button>
<button class="digit col-3 btn btn-secondary shadow-none">0</button>
<button id="equal" class="col-6 btn btn-secondary shadow-none">
=
</button>
</div>
</div>
</div>
</div>
</body>
</html>
If you debug you would see what is happening
function handleOperator(op) {
console.log('handleOperator', operator, op);
operator = op;
You will see that your op has a bunch of whitespace in it.
trim it
operator = op.trim();
or better yet use data attributes
<button class="col-3 btn btn-secondary shadow-none operation" data-value="*">*</button>
and reading it
handleOperator(e.currentTarget.dataset.value);

Bootstrap modal not showing with JavaScript " $("#attributeUpdateModal").modal('show');"

I am new to JavaScript and I'm working on a project with openlayers and geoserver and I need to add features to a layer. I succeeded to draw a feature but for saving it I need to enter its attributes which I implemented in a bootstrap modal but when I finish drawing the modal doesn't show I get just a transparent page and it stays like that.
Here it is my html code :
<!-- Attribute Update Modal -->
<div class="modal " id="attributeUpdateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLabel">Attributes</h3>
<button class="btn-close btn-light" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="attribute-body">
<div id="attributeContainer"></div>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button id="btnSave" type="button" class="btn btn-success">
Save
</button>
<button id="btnCancel" type="button" class="btn btn-warning">
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
Here it is my JavaScript code :
drawInteraction.on("drawend", function (e) {
var feature = e.feature;
feature.set("geometry", feature.getGeometry());
modifiedFeatureList.push(feature);
var featureProperties = editGeoJSON
.getSource()
.getFeatures()[0]
.getProperties();
document.getElementById("attributeContainer").innerHTML = "";
for (var key in featureProperties) {
if (featureProperties.hasOwnProperty(key)) {
if (key != "geometry") {
if (key != "id") {
var div = document.createElement("div");
div.className = "mb-3";
var lbl = document.createElement("label");
lbl.className = "form-label";
lbl.innerHTML = key;
var inputBox = document.createElement("input");
inputBox.className = "form-control";
inputBox.id = key;
inputBox.value = "";
div.appendChild(lbl);
div.appendChild(inputBox);
document.getElementById("attributeContainer").appendChild(div);
}
}
}
}
$("#attributeUpdateModal").modal('show');
});
Does anyone have an idea about this issue?

How do I get Photoswipe caption text?

I'm hoping this isn't too silly of a question, but I've been stuck on this problem for hours now and could use some help/guidance with it.
I'm using ACF Gallery in WP, and I'm now trying to turn this into a popup slider. So I decided to use the Photoswipe plugin to achieve this.
I have the slider working fine, it's just that I can't figure out how to output the image caption with each image.
<?php
$popup_gallery = get_field('popup_gallery','option');
$popup_gallery_json = json_encode($popup_gallery,JSON_FORCE_OBJECT);
?>
<div class="popup-gallery-data" data-json='<?php echo $popup_gallery_json;?>'
data-json-length="<?php echo count($popup_gallery);?>" >
</div>
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<div class="pswp__bg"></div>
<div class="pswp__scroll-wrap">
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<div class="pswp__counter"></div>
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title="Share"></button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class="pswp__share-tooltip"></div>
</div>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class="pswp__caption">
<div class="pswp__caption__center"></div>
</div>
</div>
</div>
</div>
var galleryArr = [];
var galleryJson = $('.popup-gallery-data').data('json');
// get the number of objects
var jsonLength = $('.popup-gallery-data').data('json-length');
// push each object into the array;
for (let i = 0; i < jsonLength; i++) {
galleryArr.push(galleryJson[i]);
}
$('a[href*="#popup-gallery"]').click(function (e) {
e.preventDefault();
// Prevent errors.
if (jsonLength > 0) {
popUpGallery(galleryArr);
}
})
var popUpGallery = function (data) {
const json = data;
var pswpElement = document.querySelectorAll('.pswp')[0];
// build items array
var items = [];
json.map((img) => {
items.push({
src: img.url,
w: img.width,
h: img.height
})
})
// define options (if needed)
var options = {
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
}
caption should be an available key so you can update your code like below:
json.map((img) => {
items.push({
src: img.url,
w: img.width,
h: img.height,
title: img.caption
})
})

JavaScript code working fine on codepen but not working on fiddle. Couldn't able to find

Codepen URL: https://codepen.io/pkprabu/pen/zmRqgZ
hi i'm new to JavaScript and working on some code. Problem is that the same code working fine on codepen but not working on fiddle and my page. I couldn't able to find that why its workig on codepen but not on fiddle & what is going on. I have given my codepen url above also. Please explain me & help me to fix this.
"use strict";
// vars
var result = document.querySelector(".result"),
img_result = document.querySelector(".img-result"),
img_w = document.querySelector(".img-w"),
img_h = document.querySelector(".img-h"),
options = document.querySelector(".options"),
save = document.querySelector(".save"),
cropped = document.querySelector(".cropped"),
dwn = document.querySelector(".download"),
upload = document.querySelector("#file-input"),
cropper = "";
// on change show image with crop options
upload.addEventListener("change", function(e) {
if (e.target.files.length) {
// start file reader
var reader = new FileReader();
reader.onload = function(e) {
if (e.target.result) {
$(".modal").modal("show");
// create new image
var img = document.createElement("img");
img.id = "image";
img.src = e.target.result;
// clean result before
result.innerHTML = "";
// append new image
result.appendChild(img);
// show save btn and options
save.classList.remove("hide");
options.classList.remove("hide");
// init cropper
cropper = new Cropper(img);
}
};
reader.readAsDataURL(e.target.files[0]);
}
});
// save on click
save.addEventListener("click", function(e) {
e.preventDefault();
// get result to data uri
var imgSrc = cropper.getCroppedCanvas({
width: img_w.value // input value
}).toDataURL();
// remove hide class of img
cropped.classList.remove("hide");
img_result.classList.remove("hide");
// show image cropped
cropped.src = imgSrc;
dwn.classList.remove("hide");
dwn.download = "imagename.png";
dwn.setAttribute("href", imgSrc);
});
$(".upload-button").on("click", function() {
$("#file-input").trigger("click");
});
i:hover {
cursor: pointer;
}
.dashboard-hme-img {
max-height: 100%;
max-width: 100%;
border-radius: 50%;
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
<link href="https://cdn.paperindex.com/bootstrap/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js"></script>
<!-- <input type="file" id="file-input"> -->
<p>Update</p>
<img class="dashboard-hme-img profile-pic" src="https://cdn.paperindex.com/piimages/dummy/vivek.png">
<i class="fa fa-camera upload-button"></i>
<input id="file-input" class="hidden" type="file" accept="image/*" />
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<!-- leftbox -->
<div class="box-2">
<div class="result"></div>
</div>
<!--rightbox-->
<div class="box-2 img-result hide">
<!-- result of crop -->
<img class="cropped" src="" alt="">
</div>
<!-- input file -->
<div class="box">
<div class="options hide">
<input type="hidden" class="img-w" value="200" min="200" max="1200" />
</div>
<!-- save btn -->
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button><button class="btn save hide">Save</button>
</div>
</div>
</div>
</div>
You forget CSS File cropper.min.css
https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css
https://jsfiddle.net/2gda1Lho/

Improper position during animation

I have two swap-able divs using Jquery Drag and Drop.
When I am trying to swap divs using drag the position of divs during animation is not proper. The swapping of divs is happening properly but problem is during animation.
HTML
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" id="toz">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class='droppable'>
<div class="draggable">Draggable 1</div>
</div>
<div class='droppable'>
<div class="draggable">Draggable 2</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JavaScript
$(document).ready(function() {
window.startPos = window.endPos = {};
makeDraggable();
$('.droppable').droppable({
hoverClass: 'hoverClass',
drop: function(event, ui) {
var $from = $(ui.draggable),
$fromParent = $from.parent(),
$to = $(this).children(),
$toParent = $(this);
window.endPos = $to.offset();
swap($from, $from.offset(), window.endPos, 200);
swap($to, window.endPos, window.startPos, 1000, function() {
$toParent.html($from.css({
position: 'relative',
left: '',
top: '',
'z-index': ''
}));
$fromParent.html($to.css({
position: 'relative',
left: '',
top: '',
'z-index': ''
}));
makeDraggable();
});
}
});
function makeDraggable() {
$('.draggable').draggable({
zIndex: 99999,
revert: 'invalid',
start: function(event, ui) {
window.startPos = $(this).offset();
}
});
}
function swap($el, fromPos, toPos, duration, callback) {
$el.css('position', 'absolute')
.css(fromPos)
.animate(toPos, duration, function() {
if (callback) callback();
});
}
});
Fiddle demo of problem
Simply changing absolute to fixed worked. Fiddle
function swap($el, fromPos, toPos, duration, callback) {
$el.css('position', 'fixed')
.css(fromPos)
.animate(toPos, duration, function() {
if (callback) callback();
});
}

Categories

Resources