error when loading a saved game - javascript

I've create a puzzle game yesterday and I've made a save system, but I'm getting an error when loading the save:
here's the website
and here's a save
here's the function that gets launched when loading a save:
function loadSave(){
var saveData = $("#saveText").text();
var pieceData = saveData.split("|");
var posData = [];
var puzzleInfo = pieceData[0].split(",");
createGrid(parseInt(puzzleInfo[1]));
createPieces(parseInt(puzzleInfo[1]), puzzleInfo[0]);
oldSource = imgSource;
imgSource = puzzleInfo[0];
console.log(saveData);
$("#puzzleContainer img").attr("src", imgSource);
for(i=1; i < pieceAmount+1; i++){
posData = pieceData[i].split(";");
$(".piece:nth-child("+i+")").css({
top: posData[0],
left: posData[1],
});
}
$( "#pieceAmount" ).slider({
value: puzzleInfo[1],
});
$("#pieceAmountValue").html(puzzleInfo[1]*puzzleInfo[1]);
}
after a bit of troubleshooting, I've found out that puzzleInfo[0] as nothing in it
does anybody knows why the src I'm getting from the save is empty?
edit:
here's the function that launches when an error is detected:
$("#puzzleContainer img").error(function(){
imgSource = oldSource;
createGrid(Size);
createPieces(Size, imgSource);
$("#puzzleContainer img").attr("src", imgSource);
alert("the image could not be found, is your link correct?");
});

I've figured out what was wrong
the problem was here:
var saveData = $("#saveText").text();
saveData was always empty, I needed to get the value using
var saveData = $("#saveText").val();
instead

Related

Image duplication after multiple file input

Have this issue here: I want to upload several images at once and show them directly afterwards in the browser. Everything is fine. However, doing this on mobile, sometimes I don't get all the images, but duplicates of another one from the file array. I have a suspicion, that this has to do with hardware limitations, since on PC everything works fine, but not on mobile.
Here is the fiddle. You can check it via mobile to see if duplicates appear.
So in result I get this on mobile. It wasn't two images in the selection, only one:
Here I have the Javascript snippet. Is there any room for improvement? Espacially onload processes are really confusing me from time to time. Is there any chance to write it better?
Javascript:
jQuery('.upload-mobile').change(function(){
jQuery('body').toggleClass( "loading" );
var imagecounter = jQuery(this)[0].files.length;
var loadcounter = 0;
for(var i = 0; i<imagecounter;i++){
for(var p = 1;p<=12;p++){
if(jQuery('#preview'+p).length<=0){
jQuery('.image-collection').prepend(jQuery('<div></div>',{id:'preview'+p,css:{'display':'inline-block'}}));
break;
};
}
var file = this.files[i];
var reader = new FileReader();
reader.onload = function(e){
for(var w = 1;w<=12;w++){
if(jQuery('#preview'+w).children().length>0) {
}
else{
var img = document.createElement("img");
img.src = e.target.result;
img.id = 'img'+w;
img.className += " img-responsive";
img.className += " border-blue";
img.className += " image-small";
img.className += " image-cover";
img.style.display='none';
document.getElementById("preview"+w).appendChild(img);
break;
}
}
loadcounter++;
if(loadcounter==imagecounter){
var count = jQuery('.image-collection').children().length;
jQuery('.image-small').delay('1500').fadeIn('3000', function(){
jQuery('#image-counter').text(count+'/12');
jQuery('body').removeClass( "loading" );
if( jQuery('#image-counter').text()=='12/12'){
jQuery('#upload-photos').fadeOut('200', function(){
jQuery('#three-cube-compact').fadeIn('200');
})
}
});
}
};
var image = reader.readAsDataURL(file);
}
});
EDIT:
I tried to use the forEach function. I didn't use the for each loops earlier, so I can not say much about the difference between foreach and for. I can't say if it works better or not, but I have seen less duplicates (maybe I didn't check to often to asume good functionality of it). It almost works, but maybe there is another way to make it work flawlessly?
Javascript:
jQuery('.upload-mobile').change(function(){
jQuery('body').toggleClass( "loading" );
var imagecounter = jQuery(this)[0].files.length;
var loadcounter = 0;
Array.from(this.files).forEach(function (image, index){
for(var p = 1;p<=12;p++){
if(jQuery('#preview'+p).length<=0){
jQuery('.image-collection').prepend(jQuery('<div></div>',{id:'preview'+p,css:{'display':'inline-block'}}));
break;
};
};
var reader = new FileReader();
reader.onload = function(e){
for(var w = 1;w<=12;w++){
if(jQuery('#preview'+w).children().length>0) {
}
else{
var img = document.createElement("img");
img.src = e.target.result;
img.id = 'img'+w;
img.className += " img-responsive";
img.className += " border-blue";
img.className += " image-small";
img.className += " image-cover";
img.style.display='none';
document.getElementById("preview"+w).appendChild(img);
break;
}
}
loadcounter++;
if(loadcounter==imagecounter){
var count = jQuery('.image-collection').children().length;
jQuery('.image-small').delay('1500').fadeIn('3000', function(){
jQuery('#image-counter').text(count+'/12');
jQuery('body').removeClass( "loading" );
if( jQuery('#image-counter').text()=='12/12'){
jQuery('#upload-photos').fadeOut('200', function(){
jQuery('#three-cube-compact').fadeIn('200');
})
}
});
}
};
var pic = reader.readAsDataURL(image);
});
});
EDIT2:
The fiddle was updated
EDIT3:
Added an image of the mobile screen. I also figured out it might has something to do with the file explorer on the mobile device. When I select using the first file explorer, I don't get the duplication bug:
However, by clicking on Browse ("Durchsuchen" on the image), I get to another file explorer. And using that one creates this "duplication bug":
Is there maybe a way to solve this or maybe to disable the Browse button?

JQuery - element exists in code but returns 0 when using .length()

I have spent hours trying to figure out why the $('#news-main-container').html(itemlist); isn't working and found that when I use alert($('[id="news-main-container"]').length); it returns 0, implicating the element doesnt exist but I can see the element in the code when I inspect element. The itemlist is alerting but it won't insert into #news-main-container because it thinks it doesn't exist. Does anyone know what could cause this?
//get cached News JSON
function getNewsCache(){
cache['news'] = JSON.parse(localStorage.getItem('news'));
var objCache = cache['news'].data;
objCache = JSON.parse(objCache); //Parse string to json
buildNewsList(objCache);
}
//build HTML list of news items
function buildNewsList(objCache){
var itemlist='';
$.each(objCache, function(i, jd) {
var newstitle = jd.title.rendered;
var newsexcerpt = jd.excerpt.rendered;
var newscontent = jd.content.rendered;
var newsimageid = jd.featured_media;
var thumbsrc = '';
itemlist = itemlist+'<div class="content-news-box" id="newsclick" data-newscontent="'+newscontent+'" data-newstitle="'+newstitle+'"><div class="news-thumb-img"><img height="150px" src="'+thumbsrc+'"/></div><div class="news-title">'+newstitle+'</div><div class="news-excerpt">'+newsexcerpt+'<img height="40px" class="news-arrow-right" src="img/icon-arrow-right.png"/></div></div>';
});
alert(itemlist);
alert($('[id="news-main-container"]').length); //returns 0 but I can see it in the code!!
$('#news-main-container').html(itemlist); //WHY DOESNT THIS WORK?!?!?!
}
$("#load-news").click(function(event){
$('#stage').html('');
$('#stage').css('background','none');
$("#stage").load("news.html");
var data = {};
//get cache
cache['news'] = JSON.parse(localStorage.getItem('news'));
getNewsCache();
});
I re-arranged my code so that everything comes within $( "#stage" ).load( "news.html", function() { } and that works. Thanks #The_ehT, your suggestion got me there!
Most likely you run this code before DOM is rendered, so element doesn't exist at the runtime. Try enclosing your code in "document ready"
$(function(){
// Your code
});

Set vwashape hyperlink programmatically

Is it possible to programmatically set the hyperlink of a vwashape in Javascript?
I know there is a get method to get the links(vwashape.getHyperlinks()) but is there a set method or do I need to upload the visio file to visio, change the links and reupload it again?
Ok so after some struggling I found a solution.
Because I didnt found a way to set the hyperlinks on the object. I used the vwacontroll.addhandler onselected to bypass the problem.
vwaControl.addHandler("shapeselectionchanged", onShapeSelectionChanged);
...
onShapeSelectionChanged = function(source, args) {
try {
var shape = vwaShapes.getItemById(args);
var linkArr = shape.getHyperlinks();
for (var i = 0; i < linkArr.length; i++) {
var linkUrl = linkArr[i].value;
//manipulate link
linkUrl = linkUrl.replace("origintext", "new text");
window.location.href = linkUrl;
}
} catch(ex) {
console.log("onselected " + ex);
}
};

Loading an image but onload/onerror not working as expected

I have a div
<div id='cards'>
Which I want to fill with images based on some logic. But only when images are first loaded into memory. Otherwise, through onerror I wanna fill in some text..
function pasteCard(card, to){
if (typeof(card) == 'string')
card = [card];
var image = [];
for (var i = 0; i < card.length; i++) {
image[i] = new Image();
image[i].src = '/sprites/open/' + card[i] + '.png';
image[i].onload = function() {
pasteImage(to, image[i]);
}
image[i].onerror = function() {
pasteText(to, card[i]);
}
// alert(card[i]) #1
}
function pasteImage(to, image) {
to.append(image);
}
function pasteText(to, text) {
// alert(card[i]) #2
to.append(text);
}
}
pasteCard(['ABC123', 'DEF456', 'GHI789'], $('#cards'));
But this isn't working.
Problem/weirdness: If only #2 alert is active it returns nothing. But strangely if #1 alert is also active it does kinda work... (but still doesn't load my images, and mostly fails too when other code is involved)
Question: Why is it not working without #1 alert (at least in that jsfiddle)
suggestions?: what should I do?
Onload and onerror events are fired (executed) outside the scope of your function so your variables will be undefined. In the event method you have access to this which is the image object. You can set a data attribute to each image and access that in your error event.
Here is an example:
http://jsfiddle.net/7CfEu/4/
The callbacks are not in the same scope as your image array is - therefor you need to declare a variable then will "connect the scopes" and use it inside the callbacks
also the i variable probably changes until the callback is fired - so by using it inside the callback you will get undefined behavior
for (var i = 0; i < card.length; i++) {
var current_card = card[i];
var current_image = new Image();
current_image.onload = function() {
pasteImage(to, current_image);
}
current_image.onerror = function() {
pasteText(to, current_card);
}
current_image.src = '/sprites/open/' + current_card + '.png';
image[i] = current_image;
}
Fiddle: http://jsfiddle.net/7CfEu/6/
(Also - closing the div tag is never a bad idea)
Just in case anyone ends up here for same reason I did.
Was going crazy because onload and onerror were not firing in the page I was building. Tried copy pasting
var myimage = new Image();
myimage.onload = function() { alert("Success"); };
myimage.onerror = function() { alert("Fail"); };
myimage.src = "mog.gif" //Doesn't exist.
Which was working within codepen and random otherwise blank pages.
Turns out the problem I was having was that I was doing AJAX requests earlier in the page. This involved authorization which in turn involved a call to
setRequestHeader();
This was resulting in a net::ERR_FILE_NOT_FOUND error instead of the expected GET mog.gif 404 (Not Found)
This seemed to prevent proper triggering of events.
Revert with
xhr.setRequestHeader("Authorization", "");

What event is triggered when a HTML5 Adobe Extension Panel is collapsed?

I am working on a HTML5 Adobe Extension that needs to load data from LocalStorage into some 's but for the life of me I can't figure out wether the panel is being collapsed or closed or what happens with it. The list items are generated dinamically.
I would also need an ideea to save data upon exit so that the list elements inside the UL can be saved and retrieved when PS starts again. So far I noticed that the host i a chrome type browser that supports a lot of stuff, including localstorage. However, I've not seen a dead simple tutorial for saving ul items but only for variables and strings.
right now I'm unable to save or retrieve the data from localstorage.
here is my code so far.
$(document).ready(function(){
var task = {
"name" : "",
"description" : "",
"project" : ""
};
$('#saveData').css("visibility", "hidden");
$('#btnMarkAsDone').css("visibility","hidden");
var toBeDone = Array();
var wasDone = Array();
$( window ).load(function() {
for(var i = 0;i < toBeDone.length;i++){
$('#todo').append('<li class="todo-item">'+toBeDone[i]+'</li>');
}
for(var i = 0; i < wasDone.length; i++){
$('#done').append('<li class="completed">'+wasDone[i]+'</li>');
}
});
$( window ).width(function() {
});
$("#btnAddTask").click(function(){
var oName = task.name;
var oProject = task.project;
var oDescription = task.description;
var taskname = $("#txtTaskName").val();
var taskproject = $("#txtTaskProj").val();
var taskdescription = $("#txtTaskDesc").val();
oName = taskname;
oProject = taskproject;
oDescription = taskdescription;
var input = "<b>Task: </b>"+oName+" | "+"<b>PSD: </b>"+oProject+" | "+"<b>Desc: </b>"+oDescription;
$("#todo").append('<li class="todo-item">'+input+'</li>');
});
$("#todo").on('click','li',function(){
$(this).addClass('complete');
$("#done").append(this);
});
$("#done").on('click','li',function(){
$(this).remove();
});
$("#saveData").click(function(){
if(localStorage['todo']){
toBeDone = JSON.parse(localStorage['todo']);
}if(localStorage['done']){
wasDone = JSON.parse(localStorage['done']);
}
});
$(function() {
$("button").button();
});
});
Fixed the localStorage part:
$("#saveData").click(function(){
var toDo = $('#todo').html();
var finished = $('#done').html();
localStorage.setItem('todo',toDo);
localStorage.setItem('done',finished);
});
$(window).load(function() {
$("#todo").html(localStorage.getItem('todo'));
$("#done").html(localStorage.getItem('done'));
});
Still need to find out what kind of event is fired when a window is collapsed though. I appreciate any help !

Categories

Resources