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

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 !

Related

Javascript functions do not work after updating content (Using Document Ready atm.)

I have a question I am working with a form based shopping cart add function and a livesearch (PHP) function where it requests new data with the same classes. I have seen multiple examples besides (document.ready) but none of them seemed to work correctly after the DOM Content has been modified by the PHP livesearch function. (The current method is on the document ready function as you guys can see.
Thanks in advance!
// Icon Click Focus
$('.product').on('click', function() {
var strId = '';
var strId = $(this).attr('class');
var strId2 = strId.replace(' product','');
var strId3 = strId2.replace('product-','');
var formData = "product"+strId3;
document.getElementById("product_toevoeg_id").value = strId3;
var productNaam = $("#"+formData+" .f-productnaam").val();
document.getElementById("productnaam").innerHTML = productNaam;
document.getElementById("product_naam_form").value = productNaam;
var productIngredienten = $("#"+formData+" .f-ingredienten").val();
document.getElementById("ingredienten").innerHTML = productIngredienten;
document.getElementById("ingredienten_form").value = productIngredienten;

Function stops working after retrieving localStorage

I'm using localStorage on two lists, fruit-shelf & fruit-basket.
If you click on a fruit from fruit-shelf, it appends it to the fruit-basket, and if you refresh the page it's still there — so it remembers everything as it should.
Problem is: if you add one fruit, and then refresh page, you can't add more fruits, the program completely stops working.
I've added a Clear Local Storage button, which works. If you click on it and refresh page, you can add fruits again. But as soon as one fruit is added and you refresh page, you can't add more items to the fruit-basket.
I'm not sure how to put a name on the problem so it's hard to search for solutions (I've tried!).
Can someone point me in the right direction? :-)
Fiddle (I couldn't use SO Snippet here because of localStorage):
https://jsfiddle.net/nrv269hc/7/
JS:
(function() {
var btnClearStorage = document.querySelector('.btn-delete-all');
var fruitShelf = document.querySelector('.fruit-shelf');
var fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
var fruitBasket = document.querySelector('.fruit-basket');
// Store current state of fruitSheflf & fruitBasket
function storestate() {
localStorage.fruitShelf = fruitShelf.innerHTML;
localStorage.currentFruitBasket = fruitBasket.innerHTML;
};
function retrievestate() {
// Retrieve fruits left from shelf
if (localStorage.fruitShelf) {
fruitShelf.innerHTML = localStorage.fruitShelf;
}
// Retrieve stored fruits
if (localStorage.currentFruitBasket) {
fruitBasket.innerHTML = localStorage.currentFruitBasket;
}
};
retrievestate();
for (var i = 0; i < fruitShelfItems.length; i++) {
fruitShelfItems[i].addEventListener('click', function(event) {
fruitBasket.appendChild(this);
storestate();
});
}
// Clear Local Storage
btnClearStorage.addEventListener('click', function() {
localStorage.clear(fruitShelf);
localStorage.clear(fruitBasket);
});
})();
You need to update the fruitShelfItems as the HTML is update after retrievestate.
Look at updated JsFiddle
(function() {
var btnClearStorage = document.querySelector('.btn-delete-all');
var fruitShelf = document.querySelector('.fruit-shelf');
var fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
var fruitBasket = document.querySelector('.fruit-basket');
// Store current state of fruitSheflf & fruitBasket
function storestate() {
localStorage.fruitShelf = fruitShelf.innerHTML;
localStorage.currentFruitBasket = fruitBasket.innerHTML;
};
function retrievestate() {
// Retrieve fruits left from shelf
if (localStorage.fruitShelf) {
fruitShelf.innerHTML = localStorage.fruitShelf;
}
// Retrieve fruit basket
if (localStorage.currentFruitBasket) {
fruitBasket.innerHTML = localStorage.currentFruitBasket;
}
// you need to update the fruitShelfItems as the HTML is update after retrievestate
fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
};
retrievestate();
for (var i = 0; i < fruitShelfItems.length; i++) {
fruitShelfItems[i].addEventListener('click', function(event) {
fruitBasket.appendChild(this);
storestate();
});
}
// Clear Local Storage
btnClearStorage.addEventListener('click', function() {
localStorage.clear(fruitShelf);
localStorage.clear(fruitBasket);
});
})();

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
});

error when loading a saved game

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

jQuery appending to a dynamically created div

Trying to add a save/load feature using JSON to a diagram that uses jsPlumb. The save feature works like a charm however the load feature is not able to replicate full initial saved state. That is, the problem occurs when jQuery is trying to append to a freshly/dynamically created div.
The jsfiddle has the following functionality:
I can add projects which are div containers. Inside these I can add tasks by clicking on the green projects.
http://jsfiddle.net/9yej6/1/
My saving code plugins everything into an array which then becomes a string (using JSON).
$('#saveall').click(function(e) {
// Saving all of the projects' parameters
var projects = []
$(".project").each(function (idx, elem) {
var $elem = $(elem);
projects.push({
blockId: $elem.attr('id'),
positionX: parseInt($elem.css("left"), 10),
positionY: parseInt($elem.css("top"), 10)
});
});
// Saving all of the tasks' parameters
var tasks = []
$(".task").each(function (idx, elem) {
var $elem = $(elem);
tasks.push({
blockId: $elem.attr('id'),
parentId: $elem.parent().attr('id')
});
});
// Convert into string and copy to textarea
var flowChart = {};
flowChart.projects = projects;
flowChart.tasks = tasks;
var flowChartJson = JSON.stringify(flowChart);
$('#jsonOutput').val(flowChartJson);
});
The load code does the same in reverse.
$('#loadall').click(function(e) {
// Delete everything from the container
$('#container').text("");
// Convert textarea string into JSON object
var flowChartJson = $('#jsonOutput').val();
var flowChart = JSON.parse(flowChartJson);
// Load all projects
var projects = flowChart.projects;
$.each(projects, function( index, elem ) {
addProject(elem.blockId);
repositionElement(elem.blockId, elem.positionX, elem.positionY)
});
// Try to load all tasks
var tasks = flowChart.tasks;
$.each(tasks, function( index, elem ) {
//Problem occurs here, I am unable to reference the created project
$(elem.parentId).text('This is a test');
addTask(elem.parentId, 0);
});
});
Basically, what's not working is the $(parentId).append(newState); line 75 in the jsFiddle, I can't seem to reference that div because it was just created using jquery ?
edit:
More specifically, I make use of these functions to create actual project and task divs
function addProject(id) {
var newProject = $('<div>').attr('id', id).addClass('project').text(id);
$('#container').append(newProject);
jsPlumb.draggable(newProject, {
containment: 'parent' });
}
function addTask(parentId, index) {
var newState = $('<div>').attr('id', 'state' + index).addClass('task').text('task ' + index);
$(parentId).append(newState);
}
It should be:
$('#' + parentId).append(newState);
To search for an ID in a jQuery selector, you need the # prefix.

Categories

Resources