Greeting,
I have been required to make a module for a website I am working where user can drag and drop some image on a previewed pdf. So I found a sample code in codepen:
Demo
This is done using PDFJS. As far as I understand PDFJS is completely viewer. So my question is how can I finally save the modified page after I drag and drop the image over canvas previewed page. Does PDF-Lib with the combination of PDFJS is doable for this? Or TCPDF or other backend PHP based library would needed for this purpose.
Note: Backed is done in CakePHP.
var pdfData = atob($('#pdfBase64').val());
/*
* costanti per i placaholder
*/
var maxPDFx = 595;
var maxPDFy = 842;
var offsetY = 7;
'use strict';
// The workerSrc property shall be specified.
//
pdfjsLib.GlobalWorkerOptions.workerSrc =
'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.worker.min.js';
//
// Asynchronous download PDF
//
var loadingTask = pdfjsLib.getDocument({data: pdfData});
loadingTask.promise.then(function(pdf) {
//
// Fetch the first page
//
pdf.getPage(1).then(function(page) {
var scale = 1.0;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//
// Render PDF page into canvas context
//
var renderContext = {
canvasContext: context,
viewport: viewport
};
//page.render(renderContext);
page.render(renderContext).then(function() {
$(document).trigger("pagerendered");
}, function() {
console.log("ERROR");
});
});
});
/* The dragging code for '.draggable' from the demo above
* applies to this demo as well so it doesn't have to be repeated. */
// enable draggables to be dropped into this
interact('.dropzone').dropzone({
// only accept elements matching this CSS selector
accept: '.drag-drop',
// Require a 100% element overlap for a drop to be possible
overlap: 1,
// listen for drop related events:
ondropactivate: function (event) {
// add active dropzone feedback
event.target.classList.add('drop-active');
},
ondragenter: function (event) {
var draggableElement = event.relatedTarget,
dropzoneElement = event.target;
// feedback the possibility of a drop
dropzoneElement.classList.add('drop-target');
draggableElement.classList.add('can-drop');
draggableElement.classList.remove('dropped-out');
//draggableElement.textContent = 'Dragged in';
},
ondragleave: function (event) {
// remove the drop feedback style
event.target.classList.remove('drop-target');
event.relatedTarget.classList.remove('can-drop');
event.relatedTarget.classList.add('dropped-out');
//event.relatedTarget.textContent = 'Dragged out';
},
ondrop: function (event) {
//event.relatedTarget.textContent = 'Dropped';
},
ondropdeactivate: function (event) {
// remove active dropzone feedback
event.target.classList.remove('drop-active');
event.target.classList.remove('drop-target');
}
});
interact('.drag-drop')
.draggable({
inertia: true,
restrict: {
restriction: "#selectorContainer",
endOnly: true,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
},
autoScroll: true,
// dragMoveListener from the dragging demo above
onmove: dragMoveListener,
});
function dragMoveListener (event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform ='translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
// this is used later in the resizing demo
window.dragMoveListener = dragMoveListener;
$(document).bind('pagerendered', function (e) {
$('#pdfManager').show();
var parametri = JSON.parse($('#parameters').val());
$('#parametriContainer').empty();
renderizzaPlaceholder(0, parametri);
});
function renderizzaPlaceholder(currentPage, parametri){
var maxHTMLx = $('#the-canvas').width();
var maxHTMLy = $('#the-canvas').height();
var paramContainerWidth = $('#parametriContainer').width();
var yCounterOfGenerated = 0;
var numOfMaxItem = 25;
var notValidHeight = 30;
var y = 0;
var x = 6;
var page=0;
var totalPages=Math.ceil(parametri.length/numOfMaxItem);
for (i = 0; i < parametri.length; i++) {
var param = parametri[i];
var page = Math.floor(i/numOfMaxItem);
var display= currentPage == page ? "block" : "none";
if(i > 0 && i%numOfMaxItem == 0){
yCounterOfGenerated = 0;
}
var classStyle = "";
var valore = param.valore;
/*il placeholder non è valido: lo incolonna a sinistra*/
if(i > 0 && i%numOfMaxItem == 0){
yCounterOfGenerated = 0;
}
var classStyle = "";
var valore = param.valore;
/*il placeholder non è valido: lo incolonna a sinistra*/
y = yCounterOfGenerated;
yCounterOfGenerated += notValidHeight;
classStyle = "drag-drop dropped-out";
$("#parametriContainer").append('<div class="'+classStyle+'" data-id="-1" data-page="'+page+'" data-toggle="'+valore+'" data-valore="'+valore+'" data-x="'+x+'" data-y="'+y+'" style="transform: translate('+x+'px, '+y+'px); display:'+display+'"> <span class="circle"></span><span class="descrizione">'+param.descrizione+' </span></div>');
}
y = notValidHeight * (numOfMaxItem+1);
var prevStyle = "";
var nextStyle = "";
var prevDisabled = false;
var nextDisabled = false;
if(currentPage == 0){
prevStyle = "disabled";
prevDisabled = true;
}
if(currentPage >= totalPages-1 || totalPages == 1){
nextDisabled=true;
nextStyle="disabled";
}
//Aggiunge la paginazione
$("#parametriContainer").append('<ul id="pager" class="pager" style="transform: translate('+x+'px, '+y+'px); width:200px;"><li onclick="changePage('+prevDisabled+','+currentPage+',-1)" class="page-item '+prevStyle+'"><span>«</span></li><li onclick="changePage('+nextDisabled+','+currentPage+',1)" class="page-item '+nextStyle+'" style="margin-left:10px;"><span>»</span></li></ul>');
}
function renderizzaInPagina(parametri){
var maxHTMLx = $('#the-canvas').width();
var maxHTMLy = $('#the-canvas').height();
var paramContainerWidth = $('#parametriContainer').width();
var yCounterOfGenerated = 0;
var numOfMaxItem = 26;
var notValidHeight = 30;
var y = 0;
var x = 6;
for (i = 0; i < parametri.length; i++) {
var param = parametri[i];
var classStyle = "drag-drop can-drop";
var valore = param.valore;
/*il placeholder non è valido: lo incolonna a sinistra*/
var pdfY = maxPDFy - param.posizioneY - offsetY;
y = (pdfY * maxHTMLy) / maxPDFy;
x = ((param.posizioneX * maxHTMLx) / maxPDFx) + paramContainerWidth;
$("#parametriContainer").append('<div class="'+classStyle+'" data-id="'+param.idParametroModulo+'" data-toggle="'+valore+'" data-valore="'+valore+'" data-x="'+x+'" data-y="'+y+'" style="transform: translate('+x+'px, '+y+'px);"> <span class="circle"></span><span class="descrizione">'+param.descrizione+' </span></div>');
}
}
function changePage(disabled, currentPage, delta){
if(disabled){
return;
}
/*recupera solo i parametri non posizionati in pagina*/
var parametri = [];
$(".drag-drop.dropped-out").each(function() {
var valore = $(this).data("valore");
var descrizione = $(this).find(".descrizione").text();
parametri.push({valore:valore, descrizione:descrizione, posizioneX:-1000, posizioneY:-1000});
$(this).remove();
});
//svuota il contentitore
$('#pager').remove();
currentPage += delta;
renderizzaPlaceholder(currentPage, parametri);
//aggiorna lo stato dei pulsanti
//aggiorna gli elementi visualizzati
}
function showCoordinates(){
var validi = [];
var nonValidi = [];
var maxHTMLx = $('#the-canvas').width();
var maxHTMLy = $('#the-canvas').height();
var paramContainerWidth = $('#parametriContainer').width();
//recupera tutti i placholder validi
$('.drag-drop.can-drop').each(function( index ) {
var x = parseFloat($(this).data("x"));
var y = parseFloat($(this).data("y"));
var valore = $(this).data("valore");
var descrizione = $(this).find(".descrizione").text();
var pdfY = y * maxPDFy / maxHTMLy;
var posizioneY = maxPDFy - offsetY - pdfY;
var posizioneX = (x * maxPDFx / maxHTMLx) - paramContainerWidth;
var val = {"descrizione": descrizione, "posizioneX":posizioneX, "posizioneY":posizioneY, "valore":valore};
validi.push(val);
});
if(validi.length == 0){
alert('No placeholder dragged into document');
}
else{
alert(JSON.stringify(validi));
}
}
#messageContainer{
display:none;
}
#outer-dropzone {
height: 140px;
touch-action: none;
}
#inner-dropzone {
height: 80px;
}
.dropzone {
background-color: #ccc;
border: dashed 4px transparent;
border-radius: 4px;
margin: 10px auto 30px;
padding: 10px;
width: 100%;
transition: background-color 0.3s;
}
.drop-active {
border-color: #aaa;
}
.drop-target {
background-color: #29e;
border-color: #fff;
border-style: solid;
}
.drag-drop {
display: inline-block;
position:absolute;
z-index:999;
min-width: 40px;
padding: 0em 0.5em;
padding-left:0;
color: #fff;
background-color: #29e;
border: none;
-webkit-transform: translate(0px, 0px);
transform: translate(0px, 0px);
transition: background-color 0.3s;
line-height: 10px;
padding-right: 0 !important;
padding-left: 5px !important;
}
.drag-drop.can-drop {
color: #000;
background-color: transparent;
opacity:0.9;
/* IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=90)";
/* IE 5-7 */
filter: alpha(opacity=90);
/* Netscape */
-moz-opacity: 0.9;
/* Safari 1.x */
-khtml-opacity: 0.9;
}
.nopadding {
padding: 0 !important;
margin: 0 !important;
}
.circle {
width: 10px;
height: 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
background: #323c3c;
float: left;
display: inline-block;
margin-top: 1px;
margin-right: 2px;
}
.dropped-out{
display: block;
padding: .75rem 1.25rem;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid rgba(0,0,0,.125);
width:200px;
color: black;
}
.col-fixed-240{
width:240px;
height:100%;
z-index:1;
}
.col-fixed-605{
margin-left:240px;
width:605px;
height:100%;
z-index:1;
}
.page-item{
cursor:pointer;
}
.pager{
margin-bottom:30px !important;
margin-top:0px !important;
margin-bottom: -31px !important;
}
.drag-drop.dropped-out .descrizione {
font-size: 12px !important;
}
#the-canvas{
height:842px;
width: 595px;
}
<div class="container">
<div class="row">
<div class="col-md-12" style="padding:10px">
<button class="btn btn-primary btn-block" onClick="showCoordinates()">Show PDF Placeholders Coordinates</button>
</div>
</div>
<div class="row">
<div class="col-md-12" id="pdfManager" style="display:none">
<div class="row" id="selectorContainer">
<div class="col-fixed-240" id="parametriContainer">
</div>
<div class="col-fixed-605">
<div id="pageContainer" class="pdfViewer singlePageView dropzone nopadding" style="background-color:transparent">
<canvas id="the-canvas" style="border:1px solid black"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- parameters showed on the left sidebar -->
<input id="parameters" type="hidden" value='[{"idParametro":480,"descrizione":"RAPINA","valore":"X","nota":null},{"idParametro":481,"descrizione":"CAUSAL_G00","valore":"X","nota":null},{"idParametro":482,"descrizione":"A","valore":"A","nota":null},{"idParametro":483,"descrizione":"POSTA_REGISTRATA","valore":"X","nota":null},{"idParametro":484,"descrizione":"CD","valore":"CD","nota":null},{"idParametro":485,"descrizione":"DATA_ALERT","valore":"data alert","nota":null},{"idParametro":486,"descrizione":"UP","valore":"UP","nota":null},{"idParametro":488,"descrizione":"DATA_MP","valore":"DATA1","nota":null},{"idParametro":489,"descrizione":"AL_QUALITA","valore":"AL_QUALITA","nota":null},{"idParametro":490,"descrizione":"CAUSAL_G60","valore":"X","nota":null},{"idParametro":491,"descrizione":"DATA","valore":"DATA","nota":null},{"idParametro":492,"descrizione":"DATA_DENUNCIA","valore":"data denuncia","nota":null},{"idParametro":493,"descrizione":"DATA_SPEDIZIONE","valore":"data spedizione","nota":null},{"idParametro":494,"descrizione":"DATA_LAVORAZIONE","valore":"DATA_LAVORAZIONE","nota":null},{"idParametro":495,"descrizione":"NUMERO_FAX","valore":"NUMERO_FAX","nota":null},{"idParametro":496,"descrizione":"SMARRIMENTO","valore":"X","nota":null},{"idParametro":497,"descrizione":"STRUTT_ACCETTAZIONE","valore":"STRUTT_ACCETTAZIONE","nota":null},{"idParametro":498,"descrizione":"FURTO","valore":"X","nota":null},{"idParametro":499,"descrizione":"BARCODE","valore":"BARCODE","nota":null},{"idParametro":502,"descrizione":"CAUSA_MAGGIORE","valore":"X","nota":null},{"idParametro":503,"descrizione":"PACCHI","valore":"X","nota":null},{"idParametro":504,"descrizione":"TIPOLOGIA_EVENTO","valore":"TIPOLOGIA_EVENTO","nota":null},{"idParametro":505,"descrizione":"NOTE","valore":"NOTE","nota":null},{"idParametro":506,"descrizione":"DATA_RITROVAMENTO","valore":"data ritrovamento","nota":null},{"idParametro":507,"descrizione":"DATA_ACCETTAZIONE","valore":"DATA_ACCETTAZIONE","nota":null},{"idParametro":509,"descrizione":"AREA_LOGISTICA","valore":"AREA_LOGISTICA","nota":null},{"idParametro":511,"descrizione":"DA","valore":"DA","nota":null},{"idParametro":512,"descrizione":"DATA_DENUNCIA","valore":"DATA_DENUNCIA","nota":null},{"idParametro":513,"descrizione":"TIPOLOGIA_ALERT","valore":"TIPOLOGIA","nota":null},{"idParametro":515,"descrizione":"STRUTTURA_RILIEVO","valore":"STRUTTURA_RILIEVO","nota":null},{"idParametro":516,"descrizione":"STRUTTURA_DENUNCIA","valore":"STRUTTURA_DENUNCIA","nota":null},{"idParametro":517,"descrizione":"DISPACCIO","valore":"DISPACCIO","nota":null},{"idParametro":518,"descrizione":"CMP_CP","valore":"CMP_CP","nota":null},{"idParametro":520,"descrizione":"FURTO_EFFRAZIONE","valore":"X","nota":null}]' />
<!-- Below the pdf base 64 rapresentation -->
<input id="pdfBase64" type="hidden" value="" />
Thanks
I'm struggling with something that might be a basic thing. The event bound to the button (code below) only works once. After that, nothing seems to happen again on button click. I have treated the wanted behavior in the first if statement of the blur function, but since it does not execute a second time, it seems purposeless.
<button type="button" id="openModal">Open Modal</button>
<p>some text</p>
<script>
class ModalContent{
constructor(title, text){
this.title = title;
this.text = text;
}
}
var modalObject = new ModalContent("this is the modal title", "and this is its inner text");
var openModal = document.querySelector("#openModal");
var body = document.querySelector("body");
var lorem = document.querySelector("p");
openModal.addEventListener('click', blur);
function blur(event){
if(body.querySelector("#modal") != null){
var modal = body.querySelector("#modal");
console.log(modal);
modal.style.display = "flex";
}
body.innerHTML = '<div id="initial-content">' + body.innerHTML + '</div>'
var initialContent = body.querySelector("#initial-content");
initialContent.style.filter = "blur(5px)";
// Replaced this, that does NOT work as desired in JS
// body.innerHTML = body.innerHTML + '<div id="modal"></div>';
// With this:
initialContent.insertAdjacentHTML('afterend', '<div id="modal"></div>');
var modal = body.querySelector("#modal");
modal.innerHTML =
'<h2 id="modal-title">' + modalObject.title + "</h2>" + '<div id="modal-text">' + modalObject.text + "</div>"
+ '<button id="close-modal">Close this</button>';
modal.querySelector("#modal-text").style.marginBottom = "20px";
modal.style =
"display: flex; flex-direction: column; background-color: rgba(255, 255, 255, 0.8); border: 1px solid #ccc; border-radius: 10px; box-shadow: 0px 1px 8px #ddd; color: black; text-align: center; padding: 60px; position: fixed; top: calc(50% - 206px); /* it's the raw height value */ left: calc(50% - 166.675px); * it's the raw width/2 value *";
var closeModal = modal.querySelector("#close-modal");
closeModal.addEventListener('click', closeModalFunction);
function closeModalFunction(event){
modal.style.display = "none";
if(initialContent.style.filter.search("blur") != -1)
initialContent.style.filter = "unset";
}
console.log("1st");
}
</script>
</body>
When you set the innerHTML of the body, all the event listeners on the elements get removed. Instead of adding elements to the body inside the event listener, initially put all the elements in the HTML and show or hide them as necessary.
class ModalContent {
constructor(title, text) {
this.title = title;
this.text = text;
}
}
var modalObject = new ModalContent("this is the modal title", "and this is its inner text");
var openModal = document.querySelector("#openModal");
var body = document.querySelector("body");
var lorem = document.querySelector("p");
openModal.addEventListener('click', blur);
function blur(event) {
if (body.querySelector("#modal") != null) {
var modal = body.querySelector("#modal");
//console.log(modal);
modal.style.display = "flex";
}
var initialContent = document.getElementById('initial-content');
initialContent.style.filter = "blur(5px)";
var modal = body.querySelector("#modal");
modal.innerHTML =
'<h2 id="modal-title">' + modalObject.title + "</h2>" + '<div id="modal-text">' + modalObject.text + "</div>" +
'<button id="close-modal">Close this</button>';
modal.querySelector("#modal-text").style.marginBottom = "20px";
modal.style =
"display: flex; flex-direction: column; background-color: rgba(255, 255, 255, 0.8); border: 1px solid #ccc; border-radius: 10px; box-shadow: 0px 1px 8px #ddd; color: black; text-align: center; padding: 60px; position: fixed; top: calc(50% - 206px); /* it's the raw height value */ left: calc(50% - 166.675px); * it's the raw width/2 value *";
var closeModal = modal.querySelector("#close-modal");
closeModal.addEventListener('click', closeModalFunction);
function closeModalFunction(event) {
modal.style.display = "none";
initialContent.style.filter = "unset";
}
//console.log("1st");
}
<div id="initial-content">
<button type="button" id="openModal">Open Modal</button>
<p>some text</p>
</div>
<div id="modal"></div>
I have three classes box with randomly selected image and from array items, there is a square box002 at right lower portion, this can be drag and droppped to any of three box if it find match the box will dissappear . likwise three box will dissappear.
then a class bodyblue is added to body with backgroundImage named middle bg is added to body for 10 seconds . after again 3 box appear for drag and drop.
in the second level after this three boxes are dragged&dropped and deleted, when bodyblue is added to body the backgroundImage middle bg is not appearing in for 10 seconds.
How to add bodyblue backgroundImage to body using jquery in second level and third level?
var array2 = [];
var arraycart = [];
var disparray = [];
var bg = [];
var dataURL;
var timeOut;
counter = 0;
var items = [{
label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
{label: '2',url:'https://via.placeholder.com/150x150.jpg?text=image2'},
{label: '3',url:'https://via.placeholder.com/150x150.jpg?text=image3'},
{label: '4',url:'https://via.placeholder.com/150x150.jpg?text=image4'},
{label: '5',url:'https://via.placeholder.com/150x150.jpg?text=image5'},
{label: '6',url:'https://via.placeholder.com/150x150.jpg?text=image6'},
{label: '7',url:'https://via.placeholder.com/150x150.jpg?text=image7'},
{label: '8',url:'https://via.placeholder.com/150x150.jpg?text=image8'},
{label: '9',url:'https://via.placeholder.com/150x150.jpg?text=image9'},
{label:'10',url:'https://via.placeholder.com/150x150.jpg?text=image10'}
];
var notes = ['https://via.placeholder.com/150x150.jpg?text=image1',
'https://via.placeholder.com/150x150.jpg?text=image2',
'https://via.placeholder.com/150x150.jpg?text=image3',
'https://via.placeholder.com/150x150.jpg?text=image4',
'https://via.placeholder.com/150x150.jpg?text=image5',
'https://via.placeholder.com/150x150.jpg?text=image6',
'https://via.placeholder.com/150x150.jpg?text=image7',
'https://via.placeholder.com/150x150.jpg?text=image8',
'https://via.placeholder.com/150x150.jpg?text=image9',
'https://via.placeholder.com/150x150.jpg?text=image10'
];
var tempimages = [];
var notesselected = [];
array2 = items.slice();
var item;
//----------------------------------------------change backgroundImage----------------------------------------------------------
function changemainbackground() {
debugger;
var c = document.getElementById('main');
var img = document.getElementById('main'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
// Display the url to the user
//console.log('Image URL: ' + bi);
bodycontents = document.getElementById('main');
if (counter >= 0) {
bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
d = bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
//console.log(d);
}
counter++;
//console.log("counter is"+counter);
//console.log(bodycontents);
//console.log(d);
}
//--------------------------^^^^^change backgroundImage end here^^^^^^^--------------------------------------------------------
//----------------------------------------------hiddenImage------------------------------------------------------------------------
hiddenimgnumber = 0;
var images = ['https://picsum.photos/200/300', 'https://picsum.photos/200/300', 'https://picsum.photos/200/300'];
//var bg=['https://via.placeholder.com/150x150.jpg?text=image1','https://via.placeholder.com/150x150.jpg?text=image2'];
var bg = ['https://picsum.photos/200/300?image=2', 'https://picsum.photos/200/300?image=3', 'https://picsum.photos/200/300?image=4'];
var refreshIntervalId = setInterval(function() {
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
}, 1)
function hiddenimage() {
clearInterval(refreshIntervalId);
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
//console.log(hiddenimgnumber);
hiddenimgnumber++;
}
//-------------------------------------------------^^^hidden Image ends^^^------------------------------------------------------
window.onload = function() {}
function rvalue() {
elements = document.getElementsByClassName("box");
for (var i = 0; i < elements.length; i++) {
//debugger;
elements[i].style.border = "2px solid #c57232 ";
elements[i].style.borderBottom = "5px solid #c57232 ";
//object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"
}
ptags = document.querySelectorAll('[name="values"]');
boxtags = document.getElementsByClassName("box");
//if array length is 0 then we need to identify the game as completed
if (array2.length === 0) {
alert('Game completed');
return;
}
for (var index = 0; index < 3; index++) {
randomIndex = Math.floor(Math.random() * array2.length)
item = array2[randomIndex];
array2.splice(randomIndex, 1);
try {
//ptags[index].style.visibility = "visible";
//ptags[index].textContent = "RS."+item.label;
ptags[index].dataset.itemLabel = item.label;
//using label as an identity
tempimages.push({
data: item,
label: item.label
});
notesselected.push({
data: item.url,
label: item.label
});
boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
} catch (err) {
// console.log('Exception');
}
}
var tlen = tempimages.length;
}
function displayAllImages() {
try {
if (tempimages.length == 0) {
rvalue();
}
if (tempimages.length === 0) {
image = document.getElementById('slide');
image.style.display = 'none';
return;
}
// getting random item from the available items
var arr2 = tempimages;
item = arr2[Math.floor(Math.random() * arr2.length)]
image = document.getElementById('slide');
//getting notes item
//console.log(item);
///////console.log(item.label);
var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
//var dataURL =item.url;
//var dataURL = item.label;
console.log(dataURL);
image.src = dataURL;
image.dataset.itemLabel = item.label;
} catch (err) {
//console.log(err.message);
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var x = document.getElementById("slide").dataset.itemLabel;
var y = ev.target.dataset.itemLabel;
//add improvisation box drag is valid
if (ev.target.tagName === "DIV") {
y = ev.target.children[0].dataset.itemLabel;
}
//console.log(x);
//console.log(y);
if (x == y) {
ev.currentTarget.style.backgroundColor = 'initial';
ev.currentTarget.style.backgroundImage = 'initial';
ev.currentTarget.style.border = 'initial';
var pParagraph = ev.currentTarget.firstElementChild;
pParagraph.style.visibility = "hidden";
item = this.item;
tempimages = tempimages.filter(a => a.label !== item.label);
if (tempimages.length == 0) {
rvalue();
hiddenimage();
animateCongrat();
}
displayAllImages();
} else {
}
}
//----------------------------->>>animate congarat starts here-------------------------------------------------------------
var timeOut;
function animateCongrat() {
//debugger;
$('.congrats').show();
clearTimeout(timeOut);
addBlueBody();
hideCongratAndBlueBody();
}
function addBlueBody() {
$("html").css("background-color", " #070755 ");
$('body').addClass('bodyblue')
//console.log(url);
$('#container').hide();
$('#2container').hide();
$('#3container').hide();
$('#2').hide();
$('.completed').hide();
}
function hideCongratAndBlueBody() {
timeOut = setTimeout(() => {
$('.congrats').hide();
$("html").css("background-color", "");
$('body').removeClass('bodyblue')
$('#container').show();
$('#2container').show();
$('#3container').show();
$('#2').show();
$('.completed').hide();
changemainbackground();
}, 10000);
}
//----------------------------->>>animate congarat ends here-------------------------------------------------------------
body {
overflow: hidden;
}
.dashed {
border: 2px dashed #999 !important;
}
.bodyblue {
background-image: url(https://via.placeholder.com/1000x600?text=Middle+bg);
height: 100vh;
width: 100vw;
}
ul {
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
}
.box {
width: calc(33.3% - 4px);
border-radius: 5px;
border: #000 border-color: #e6e600;
margin: -2px;
background-color: #99ffff;
height: 16vh;
display: inline-flex;
align-items: center;
justify-content: center;
background-repeat: no-repeat;
background-size: cover;
cursor: pointer;
}
.box002 {
position: absolute;
top: 40.3vh;
left: 50.98vw;
cursor: pointer;
border: 2px solid black;
}
.box002 img {
width: 15.0vw;
height: 15.0vh;
border-radius: 0%;
}
#container {
white-space: nowrap;
border: px solid #CC0000;
}
.containerr {
border: px solid #FF3399;
}
.pic {
background-size: 100% 100%;
}
.container2 {
width: 29.0vw;
position: fixed;
top: 23.9vh;
left: 19.2vw;
}
body {
background-image: url(https://picsum.photos/200/300?image=0);
background-size: 100vw 100vh;
}
.reset img:hover {
opacity: 1
}
.hiddenimage {
position: absolute;
top: 4.3vh;
left: 50vw;
cursor: pointer;
}
.hiddenimage img {
width: 10.3vw;
height: 10.5vh;
border-radius: 15%;
}
.hand {
position: absolute;
top: 45.3vh;
left: 17vw;
cursor: pointer;
}
.hand img {
width: 25.3vw;
height: 25.5vh;
border-radius: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container2">
<div class="containerr">
<div class="pic" id="content">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
</div>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" border="rounded" />
</div>
<div class="congrats">
<div class="hiddenimage" style="display:none;">
<img src="" id="hiddenimageid" />
</div>
</div>
I have three class boxes with a randomly selected image and from array items. There is a square box002 at right lower portion, this can be drag and dropped to any of three boxes. If it finds a match, the box will disappear, likewise, box three will disappear.
Then a class named bodyblue is added to the body with a backgroundImage named middle bg is added to body for 10 seconds. After again box three appears for drag and drop.
The problem I am having is:
In the second level after three boxes are dragged & dropped and deleted, when bodyblue is added to body the backgroundImage middle bg is not appearing in for 10 seconds.
How do I add bodyblue backgroundImage to body using jquery in second level and third level?
var array2 = [];
var arraycart = [];
var disparray = [];
var bg = [];
var dataURL;
var timeOut;
counter = 0;
var items = [{
label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
{label: '2',url:'https://via.placeholder.com/150x150.jpg?text=image2'},
{label: '3',url:'https://via.placeholder.com/150x150.jpg?text=image3'},
{label: '4',url:'https://via.placeholder.com/150x150.jpg?text=image4'},
{label: '5',url:'https://via.placeholder.com/150x150.jpg?text=image5'},
{label: '6',url:'https://via.placeholder.com/150x150.jpg?text=image6'},
{label: '7',url:'https://via.placeholder.com/150x150.jpg?text=image7'},
{label: '8',url:'https://via.placeholder.com/150x150.jpg?text=image8'},
{label: '9',url:'https://via.placeholder.com/150x150.jpg?text=image9'},
{label:'10',url:'https://via.placeholder.com/150x150.jpg?text=image10'}
];
var notes = ['https://via.placeholder.com/150x150.jpg?text=image1',
'https://via.placeholder.com/150x150.jpg?text=image2',
'https://via.placeholder.com/150x150.jpg?text=image3',
'https://via.placeholder.com/150x150.jpg?text=image4',
'https://via.placeholder.com/150x150.jpg?text=image5',
'https://via.placeholder.com/150x150.jpg?text=image6',
'https://via.placeholder.com/150x150.jpg?text=image7',
'https://via.placeholder.com/150x150.jpg?text=image8',
'https://via.placeholder.com/150x150.jpg?text=image9',
'https://via.placeholder.com/150x150.jpg?text=image10'
];
var tempimages = [];
var notesselected = [];
array2 = items.slice();
var item;
//change backgroundImage
function changemainbackground() {
bodycontents = document.getElementById('main');
if (counter >= 0) {
bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
d = bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
}
counter++;
}
hiddenimgnumber = 0;
var images = ['https://picsum.photos/200/300', 'https://picsum.photos/200/300', 'https://picsum.photos/200/300'];
//var bg=['https://via.placeholder.com/150x150.jpg?text=image1','https://via.placeholder.com/150x150.jpg?text=image2'];
var bg = ['https://picsum.photos/200/300?image=2', 'https://picsum.photos/200/300?image=3', 'https://picsum.photos/200/300?image=4'];
var refreshIntervalId = setInterval(function() {
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
}, 1)
function hiddenimage() {
clearInterval(refreshIntervalId);
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
//console.log(hiddenimgnumber);
hiddenimgnumber++;
}
window.onload = function() {}
function rvalue() {
elements = document.getElementsByClassName("box");
for (var i = 0; i < elements.length; i++) {
//debugger;
elements[i].style.border = "2px solid #c57232 ";
elements[i].style.borderBottom = "5px solid #c57232 ";
//object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"
}
ptags = document.querySelectorAll('[name="values"]');
boxtags = document.getElementsByClassName("box");
if (array2.length === 0) {
alert('Game completed');
return;
}
for (var index = 0; index < 3; index++) {
randomIndex = Math.floor(Math.random() * array2.length)
item = array2[randomIndex];
array2.splice(randomIndex, 1);
try {
//ptags[index].style.visibility = "visible";
//ptags[index].textContent = "RS."+item.label;
ptags[index].dataset.itemLabel = item.label;
//using label as an identity
tempimages.push({
data: item,
label: item.label
});
notesselected.push({
data: item.url,
label: item.label
});
boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
} catch (err) {
// console.log('Exception');
}
}
var tlen = tempimages.length;
}
function displayAllImages() {
try {
if (tempimages.length == 0) {
rvalue();
}
if (tempimages.length === 0) {
image = document.getElementById('slide');
image.style.display = 'none';
return;
}
var arr2 = tempimages;
item = arr2[Math.floor(Math.random() * arr2.length)]
image = document.getElementById('slide');
//getting notes item
//console.log(item);
///////console.log(item.label);
var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
//var dataURL =item.url;
//var dataURL = item.label;
console.log(dataURL);
image.src = dataURL;
image.dataset.itemLabel = item.label;
} catch (err) {
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var x = document.getElementById("slide").dataset.itemLabel;
var y = ev.target.dataset.itemLabel;
if (ev.target.tagName === "DIV") {
y = ev.target.children[0].dataset.itemLabel;
}
if (x == y) {
ev.currentTarget.style.backgroundColor = 'initial';
ev.currentTarget.style.backgroundImage = 'initial';
ev.currentTarget.style.border = 'initial';
var pParagraph = ev.currentTarget.firstElementChild;
pParagraph.style.visibility = "hidden";
item = this.item;
tempimages = tempimages.filter(a => a.label !== item.label);
if (tempimages.length == 0) {
rvalue();
hiddenimage();
animateCongrat();
}
displayAllImages();
} else {
}
}
//animate congarat starts here
var timeOut;
function animateCongrat() {
$('.congrats').show();
clearTimeout(timeOut);
addBlueBody();
hideCongratAndBlueBody();
}
function addBlueBody() {
$("html").css("background-color", " #070755 ");
$('body').addClass('bodyblue')
$('#container').hide();
$('#2container').hide();
$('#3container').hide();
$('#2').hide();
$('.completed').hide();
}
function hideCongratAndBlueBody() {
timeOut = setTimeout(() => {
$('.congrats').hide();
$("html").css("background-color", "");
$('body').removeClass('bodyblue')
$('#container').show();
$('#2container').show();
$('#3container').show();
$('#2').show();
$('.completed').hide();
changemainbackground();
}, 5000);
}
body {
overflow: hidden;
}
.dashed {
border: 2px dashed #999 !important;
}
.bodyblue {
background-image: url(https://via.placeholder.com/1000x600?text=Middle+bg);
height: 100vh;
width: 100vw;
}
ul {
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
}
.box {
width: calc(33.3% - 4px);
border-radius: 5px;
border: #000 border-color: #e6e600;
margin: -2px;
background-color: #99ffff;
height: 16vh;
display: inline-flex;
align-items: center;
justify-content: center;
background-repeat: no-repeat;
background-size: cover;
cursor: pointer;
}
.box002 {
position: absolute;
top: 30.3vh;
left: 50.98vw;
cursor: pointer;
border: 2px solid white;
}
.box002 img {
width: 15.0vw;
height: 15.0vh;
border-radius: 0%;
}
#container {
white-space: nowrap;
border: px solid #CC0000;
}
.containerr {
border: px solid #FF3399;
}
.pic {
background-size: 100% 100%;
}
.container2 {
width: 29.0vw;
position: fixed;
top: 10.9vh;
left: 19.2vw;
}
body {
background-image: url(https://picsum.photos/200/300?image=0);
background-size: 100vw 100vh;
}
.reset img:hover {
opacity: 1
}
.hiddenimage {
position: absolute;
top: 4.3vh;
left: 50vw;
cursor: pointer;
}
.hiddenimage img {
width: 10.3vw;
height: 10.5vh;
border-radius: 15%;
}
.hand {
position: absolute;
top: 45.3vh;
left: 17vw;
cursor: pointer;
}
.hand img {
width: 25.3vw;
height: 25.5vh;
border-radius: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="main">
<div class="container2">
<div class="containerr">
<div class="pic" id="content">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
</div>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" border="rounded" />
</div>
<div class="congrats">
<div class="hiddenimage" style="display:none;">
<img src="" id="hiddenimageid" />
</div>
</div>
</body>
I have an issue with CSS/JS slider.
I've used simple method to make it work - bigger element (container) inside smaller (area) with hidden overflow.
I have buttons above slider btn & btn2 to control movement of bigger element (containter)
The issue is that it only work until the "first slide" (blue) is reached, then its not possible to slide to second one (red).
Fiddle: https://jsfiddle.net/26r32hb6
var button = document.querySelector('.btn');
var button2 = document.querySelector('.btn2');
var container = document.querySelector('.container');
button.style.background = 'blue';
button2.style.background = 'blue';
container.style.backgroundColor = 'blue';
button.onclick = function() {
if (container.style.left == 0) {
container.style.left = '-100.5%';
container.style.backgroundColor = 'red';
button.style.backgroundColor = 'red';
button2.style.backgroundColor = 'red';}
else if (container.style.left == '-100.5%') {
container.style.left = '-200.5%';
container.style.backgroundColor = 'purple';
button.style.backgroundColor = 'purple';
button2.style.backgroundColor = 'purple';
}
};
button2.onclick = function() {
if (container.style.left == '-100.5%') {
container.style.left = 0;
container.style.backgroundColor = 'blue';
button.style.backgroundColor = 'blue';
button2.style.backgroundColor = 'blue';}
else if (container.style.left == '-200.5%') {
container.style.left = '-100.5%';
container.style.backgroundColor = 'red';
button.style.backgroundColor = 'red';
button2.style.backgroundColor = 'red';
}
};
.wrapbtns {
width: 365px;
height: 50px;
background: yellow;
}
.btn {
width: 50px;
height: 50px;
float: right;
}
.btn2 {
width: 50px;
height: 50px;
float: left;
margin-right: 5px;
}
.btn, .btn2 {
transition-duration: 1s;
display: flex;
justify-content: center;
align-items: center;
color: white;
cursor: pointer;
}
.area {
width: 365px;
height: 250px;
overflow: hidden; /* This */
position: relative;
}
.container {
background: blue;
width: 1100px;
height: 250px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: left;
align-items: center;
left: 0;
position: absolute;
transition-duration: 1s;
}
.box {
background: yellow;
min-width: 100px;
height: 100px;
margin: 1%;
display: flex;
justify-content: center;
align-items: center;
color: black;
font-size: 48px;
transition-duration: 500ms;
}
<div class="wrapbtns">
<div class="btn2">-X</div>
<div class="btn">X</div></div>
<div class="area">
<div class="container">
<div class="box">a</div>
<div class="box">b</div>
<div class="box">c</div>
<div class="box">d</div>
<div class="box">e</div>
<div class="box">f</div>
<div class="box">g</div>
<div class="box">h</div>
<div class="box">i</div>
<div class="box">j</div>
<div class="box">k</div>
<div class="box">l</div>
<div class="box">m</div>
<div class="box">n</div>
<div class="box">o</div>
<div class="box">p</div>
<div class="box">q</div>
<div class="box">r</div>
</div>
</div>
First of all, all this can be much easier if you use something like jQuery.
but assuming that you only want to do this using javascript, here is my solution:
(Note: even if you use jQuery, the technique is quite similar to the one explained below)
FIDDLE: https://jsfiddle.net/Bintang/kvowcj6w/
var button = document.querySelector('.btn');
var button2 = document.querySelector('.btn2');
var container = document.querySelector('.container');
var area = document.querySelector('.area');
button.style.background = 'blue';
button2.style.background = 'blue';
container.style.backgroundColor = 'blue';
var slideCurrent = 0;
var slideTotal = Math.floor(container.offsetWidth / area.offsetWidth);
var slideWidth = area.offsetWidth;
var slideColors = ['blue', 'red', 'purple'];
button.onclick = function() {
if (slideCurrent < slideTotal - 1) {
var left = container.style.left;
var leftInInteger = parseInt(left.replace("px", "")) || 0;
container.style.left = (leftInInteger - slideWidth) + "px"
slideCurrent += 1;
//STYLING
container.style.backgroundColor = slideColors[slideCurrent];
button.style.backgroundColor = slideColors[slideCurrent];
button2.style.backgroundColor = slideColors[slideCurrent];
}
};
button2.onclick = function() {
if (slideCurrent > 0) {
var left = container.style.left;
var leftInInteger = parseInt(left.replace("px", "")) || 0;
container.style.left = (leftInInteger + slideWidth) + "px";
slideCurrent -= 1;
//STYLING
container.style.backgroundColor = slideColors[slideCurrent];
button.style.backgroundColor = slideColors[slideCurrent];
button2.style.backgroundColor = slideColors[slideCurrent];
}
};
Explanation:
instead of using if & else to set the specific value of "left" every single time you want to slide, what you want to do is increment the value of "left" every time you want to slide to the left & decrement the value every time you want to slide to the right. (look at the code below)
var slideCurrent = 0;
var slideTotal = Math.floor(container.offsetWidth / area.offsetWidth);
var slideWidth = area.offsetWidth;
var slideColors = ['blue', 'red', 'purple'];
button.onclick = function() {
if (slideCurrent < slideTotal - 1) {
var left = container.style.left;
var leftInInteger = parseInt(left.replace("px", "")) || 0;
container.style.left = (leftInInteger - slideWidth) + "px"
slideCurrent += 1;
//STYLING
container.style.backgroundColor = slideColors[slideCurrent];
button.style.backgroundColor = slideColors[slideCurrent];
button2.style.backgroundColor = slideColors[slideCurrent];
}
};
What the code above do is:
1.Every time the button is clicked it will check if the current slide is the last slide
if (slideCurrent < slideTotal - 1) {
2.if it's not the last slide it will get the current "left" value of the "container" then it will remove the "px" and turn it from string into an
integer(using the parseInt() function), but if the "left" property hasn't been defined it will be replaced with the value of "0"
var left = container.style.left;
var leftInInteger = parseInt(left.replace("px", "")) || 0;
3.Now that it had the current value of "left" in integer it can decrement the value by the width of the "area"(the smaller element on top) so it will slide to the right and increment the slideCurrent variable by one
container.style.left = (leftInInteger - slideWidth) + "px"
slideCurrent += 1;
4.Lastly, it will set the color of the "container" to the specified color
//STYLING
container.style.backgroundColor = slideColors[slideCurrent];
button.style.backgroundColor = slideColors[slideCurrent];
button2.style.backgroundColor = slideColors[slideCurrent];
Then you can do the opposite to slide to the other direction.