Drag element to same page on another browser - javascript

I have made a todo list my with drag and drop.I can add tasks and drag them to other categories and I can even move them to another tab where my app
is running(I can move it from one chrome tab to another).Hoewever I cannot do the following.Drag one task from chrome to firefox and vice-versa.Is that possible?
Here is jsfiddle:
https://jsfiddle.net/0feq1a12/1/
And for you who want to see code right now:
//Generate a UUID per tab
//this will help us identify when a droppedTask comes from the same page or not
var uuidGenerator =(function() {
var self = {};
var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
self.generate = function() {
var d0 = Math.random()*0xffffffff|0;
var d1 = Math.random()*0xffffffff|0;
var d2 = Math.random()*0xffffffff|0;
var d3 = Math.random()*0xffffffff|0;
return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+
lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+
lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+
lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];
}
return self;
})();
var tabUUID = uuidGenerator.generate();
var taskIndex = 0;
/*
* #param event A jQuery event that occurs when an .droppable is being dragged
*/
function dragStartHandler(event){
//e refers to a jQuery object
//that does not have dataTransfer property
//so we have to refer to the original javascript event
var originalEvent = event.originalEvent;
//We want to store an object that contains the task description and its id
//We will use this object to be able to move a task from one browser to another
$target = $(event.target);
var taskToMove = {
description:$target.text(),
id:$target.data("task-id"),
tabUUID:$target.data("tab-uuid")
};
originalEvent.dataTransfer.setData("application/json",JSON.stringify(taskToMove));
originalEvent.dataTransfer.effectAllowed = "move";
}
/*
* #param event A jQuery event that occurs when a .droppable as been dropped
*/
function dropHandler(event){
event.preventDefault();
event.stopPropagation();
var originalEvent = event.originalEvent;
var droppedTask = JSON.parse(originalEvent.dataTransfer.getData("application/json"));
var droppedItem;
var taskExistsInView = droppedTask["uuid"] != tabUUID;
if(taskExistsInView){
//The dragged task comes from the same page so we can remove it from its previous category
//and move it to the new one
droppedItem = $(`body [data-task-id=${droppedTask["id"]}]`);
}
else{
//Well well well
//The dragged task comes from another tab/browser
//We can't remove it but we can create it in the current window
//using the data provided from the droppedTask object
droppedItem = $(`<div class='list-group-item droppable' draggable='true'>${droppedTask['description']}</div>`);
droppedItem.data({"task-id":taskIndex++,"tab-uuid":tabUUID});
}
var category = $(this).parent(".box").data("category");
//Change the data-category-group of the dropped item
//and move it from its original position to the new one
droppedItem.data("category",category).appendTo($(this));
}
/*
* #param The id of the task we want to delete
*/
function deleteTask(taskId){
//Find the task with the given taskId
var taskToDelete = $("body").find(`[data-task-id='${taskId}']`);
//Remove it
taskToDelete.remove();
}
function createTask(taskElement){
//Creates a task div and appends
//it to its parent category
var taskId = taskElement["id"];
var taskText = taskElement["text"];
var taskCategory = taskElement["category"];
var taskToAppend = $(`<div class='list-group-item droppable' draggable='true' data-task-id='${taskId}' data-category='${taskCategory}'>${taskText}</div>`);
taskToAppend.data("tab-uuid",tabUUID);
//Find the dropTarget to append the created task
var dropTarget = $("body").find(`[data-category='${taskCategory}'] .dropTarget`);
taskToAppend.appendTo(dropTarget);
}
function saveTasks(){
var isLocalStorageSupported = !!localStorage;
if(!isLocalStorageSupported){
//localStorage is not supported so exit the function
return;
}
//Collect all tasks
var tasks = $(".droppable");
//This array will store everything needed for a task in order to be saved
var dataToStore = [];
for(var i=0,max =tasks.length;i<max;i++){
var currentTask = tasks[i];
//For each task we need to store
//its text, and its category
//It will be reassigned a unique id and a tabUUID after it is loaded back from localStorage
var taskData = {
text:$(currentTask).text(),
category:$(currentTask).data("category")
};
dataToStore[i]=taskData;
}
localStorage.setItem("taskList",JSON.stringify(dataToStore));
alert("Tasks have been saved");
}
function loadTasks(){
//Load tasks from localStorage
var isLocalStorageSupported = !!localStorage;
if(!isLocalStorageSupported || !localStorage.getItem("taskList")){
//Maybe localStorage is not supported or maybe there are no data saved
return;
}
var loadedTasksList = JSON.parse(localStorage.getItem("taskList"));
for(var i = 0,max = loadedTasksList.length;i<max;i++){
loadedTasksList[i].id = i;
createTask(loadedTasksList[i]);
}
}
$(document).ready(function(){
loadTasks();
//When a new task/item is created it is assigned a unique data attribute which is the task index
taskIndex =$(".list-group-item").length;
$("#saveTasksBtn").on("click",saveTasks);
$("#deleteAllTasksBtn").on("click",function(){
var answer = confirm("Are you sure you want to delete all tasks?");
if(answer){
$(".droppable").remove();
taskIndex = 0;
alert("Tasks removed");
}
});
$(".createTask").on("click",function(){
//Find the category in which the clicked plus symbol belongs to
var currentCategory = $(this).parent("h1").parent(".box");
var categoryId = currentCategory.data("category");
//Create a new task
var task = $(`<div class='list-group-item droppable' draggable='true' data-task-id='${taskIndex}' data-category='${categoryId}' data-tab-uuid='${tabUUID}'></div>`);
//Ask the user for a task description
var taskDescription = prompt("Enter task description");
if(taskDescription){
//If the user wants to create a non empty task
task.text(taskDescription);
taskIndex++;
}else{
//User has left the task description empty
//so exit
return;
}
//Append the new task to the clossest dropTarget
//by finding the dropTarget that is available in our currentCategory
task.appendTo(currentCategory.find(".dropTarget"));
});
$("body").on("dragstart",".droppable",dragStartHandler);
$("body").on("dblclick",".droppable",function(){
//Ask the user for a new task description
var newTaskDescription = prompt("Enter a new description for this task");
if(newTaskDescription){
//Update the task description
$(this).text(newTaskDescription);
}
});
$(".dropTarget").on("dragenter",function(event){
event.preventDefault();
event.stopPropagation();
}).on("dragover",false)
.on("drop",dropHandler);
$("#dangerZone").on("dragenter",function(event){
event.preventDefault();
event.stopPropagation();
}).on("dragover",false)
.on("drop",function(event){
//What we need to check first is if the dropped task comes from the same page
var droppedTask = JSON.parse(event.originalEvent.dataTransfer.getData("application/json"));
var droppedTaskTabUUID = droppedTask["tabUUID"];
if(droppedTaskTabUUID != tabUUID){
alert("Task comes from another page and cannot be deleted");
return;
}else{
var droppedTaskId = droppedTask["id"];
var answer = confirm("Are you sure you want to delete this task?");
if(answer){
deleteTask(droppedTaskId);
}
}
});
});

Related

How to remove last <li> child together with it's local storage?

I'm doing a to do list and I want to add, remove and clear tasks together with their local storage. Add and clear work but I failed to make remove work.
I tried using element.lastChild but removing it didn't work.
var last = document.getElementById("list").lastChild.innerHTML;
Here is my code
var remove = function(){
var listItems = document.getElementById("list").getElementsByTagName("li");
var last = listItems[listItems.length - 1];
last.parentNode.removeChild(last);
removeStore(last);
}
// localStorage
function store() {
window.localStorage.myToDoList = list.innerHTML;
}
function clearStore() {
localStorage.clear();
}
function removeStore(item) {
localStorage.removeItem(item);
}
Remove works only for removing tasks but I'm getting an error after the first clicking on remove button
"TypeError: last.parentNode is null"
and after the last one:
TypeError: document.getElementById(...).lastChild is null
https://codepen.io/aggat/pen/PrQRYj
You can replace your javascript part of the code with my part. The changed part is commented in capitals and explained with the purpose of change.
var add = function(){
var listItems = document.getElementById("list").getElementsByTagName("li");
var what = document.getElementById('what').value;
var li = document.createElement('li');
if (what.length > 0) {
li.appendChild(document.createTextNode(what));
list.appendChild(li);
store()
//document.getElementById('what').placeholder = "What do I have to do?";
} else {
li.appendChild(document.createTextNode("Task number " + (listItems.length + 1)));
list.appendChild(li);
store();
}
}
// I HAVE TO CHANGE THE LOGIC OF THIS FUNCTION COMPLETELY
// THIS FUNCTION TAKES VALUE FROM LOCAL STORAGE, CHECKS FOR EXISISTENCE OF
// LAST li ELEMENT HTML AND IF FIND IT, THEN REMOVE IT FROM LOCAL STORAGE VALUE
// AND SET NEW VALUE BACK IN LOCAL STORAGE
function rem() {
//var a = document.getElementById("list").lastChild.innerHTML;
//localStorage.last = a;
var aValue = localStorage.getItem("myToDoList");
console.log(aValue);
var listItems = document.getElementById("list").getElementsByTagName("li");
console.log(listItems);
if (listItems.length > 0) {
var last = listItems[listItems.length - 1];
if (last) {
var lastHtml = last.outerHTML;
console.log(lastHtml);
var indexAtWhichLastElementPresent = aValue.indexOf(lastHtml);
if (indexAtWhichLastElementPresent > -1) {
// Removes the lastElementHtml part from local storage value
aValue = aValue.substring(0, indexAtWhichLastElementPresent) + aValue.substring(indexAtWhichLastElementPresent + lastHtml.length);
}
}
}
localStorage.setItem("myToDoList", aValue);
}
var remove = function(){
var listItems = document.getElementById("list").getElementsByTagName("li");
console.log(listItems);
var last = listItems[listItems.length - 1];
rem(); // CHANGED THE CALLING ORDER. FIRST REMOVE DATA FROM LOCAL STORAGE AND THEN ELEMENT WILL BE REMOVED
last.parentNode.removeChild(last);
// TAKE OUT THE REMOVE FUNCTION FROM INSIDE OF THIS FUNCTION SO THAT IT CAN
// BE USED BY SOME OTHER FUNCTION IN FUTURE
if (listItems.length === 0){
alert();
}
}
var clearAll = function(){
var myNode = document.getElementById("list");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
clearStore();
}
alert();
}
// localStorage
function store() {
window.localStorage.myToDoList = list.innerHTML;
}
function clearStore() {
localStorage.clear();
}
/*function removeStore(item) {
localStorage.removeItem(item);
}*/
function getValues() {
var storedValues = window.localStorage.myToDoList;
if(!storedValues) {
list.innerHTML = '';
}
else {
list.innerHTML = storedValues;
}
}
getValues();
//modal box
var modal = document.getElementById("myModal");
//button that opens the modal
var btn = document.getElementById("myBtn");
//<span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
//open the modal
function alert() {
modal.style.display = "block";
}
//clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
//clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
Please comment if in case you face any problem in implementing this solution.
Your last is available only if you have entries in your todo list. Initially, and after clearing all items from your todo list, last in your remove() function will be undefined as your list is empty.
To avoid this error, conditionally check for the presence of entries in your todo list.
var remove = function(){
var listItems = document.getElementById("list").getElementsByTagName("li");
var last = listItems[listItems.length - 1];
if (last) {
last.parentNode.removeChild(last);
}
... rest of your code
}
And after removing item from your list, set your localstorage with current elements of your list. This will update your localstorage with currrent items in the list.
if (last) {
last.parentNode.removeChild(last);
window.localStorage.myToDoList = document.getElementById("list").innerHTML; // or call your store(); function
}
Hope this is helpful :)

How can I script a Google Form from a Spreadsheet to go to a specific page based on an answer?

I have successfully created a Google form that populates from a spreadsheet using code adapted from here: https://www.youtube.com/watch?v=BYA4URuWw0s . Now I would like to make the form go to a specific question based on the answer of a previous question without losing the function of updating from the spreadsheet. I have tried to alter code from here: How to assign Go_To_Page in Form Service on Multiple Choice? , but have yet to have any luck. Below is what I have as of now. I am very new to coding and any help will be greatly appreciated. Thanks in advance!!!
//insert your form ID
var FORM_ID = '1iA8jX720Eqi_GKwiA1RJiWwzt3vJ8XOOAqh-SjO9mXM';
//insert your sheet name with a list
var EMP_SHEET_NAME = 'empROSTER';
//insert your range of lis
//insert list id (before run getItemsOfForm function and look at t as A1Notation
var range1 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM_ID = '1097376824';
/*
add date question? -
form.addDateItem()
.setTitle('Date of Work Performed')
*/
//insert your sheet name with a list
var JOB_SHEET_NAME = 'jobROSTER';
//insert your range of list as A1Notation
var range2 = 'C2:C';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM2_ID = '773657499';
//insert your sheet name with a list
var AT_SHEET_NAME = '300';
//insert your range of list as A1Notation
var range3 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM3_ID = '1884670833';
//insert your sheet name with a list
var DT_SHEET_NAME = '1000';
//insert your range of list as A1Notation
var range4 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM4_ID = '379969286';
//insert your sheet name with a list
var CT_SHEET_NAME = '2000';
//insert your range of list as A1Notation
var range5 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM5_ID = '128282987';
//insert your sheet name with a list
var HOURS_SHEET_NAME = 'hourROSTER';
//insert your range of list as A1Notation
var range6 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM6_ID = '1385334889';
//Section in question
function createGoTo(){
var af = FormApp.openById(FORM_ID);
var pAdmin = af.getItemById(AT_SHEET_NAME); //use findPageIds to get the page id of a pre-created page
var pDesign = af.getItemById(DT_SHEET_NAME);
var pCon = af.getItemById(CT_SHEET_NAME);
var item = ITEM2_ID
//create choices as an array
var choices = [];
choices.push(item.createChoice('Administration Job', pAdmin));
choices.push(item.createChoice('Design Job', pDesign));
choices.push(item.createChoice('Construction Job', pCon));
// assignes the choices for the question
item.setChoices(choices);
}
function findPageIds(){
var af = FormApp.getActiveForm();
var pages = af.getItems(FormApp.ItemType.PAGE_BREAK);
for (i in pages){
var pName = pages[i].getTitle();
var pId = pages[i].getId();
Logger.log(pName+":"+pId);
}
}
//End of section in question
function updateEmpName() {
var values_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(EMP_SHEET_NAME).getRange(range1).getValues();
values_[0][0] = values_[0][0].toString();
for(var i = 1; i < values_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values_[i][0] != "") {
values_[0].push(values_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM_ID);
list.asListItem().setChoiceValues(values_[0]);
}
function updateJobName() {
var values2_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(JOB_SHEET_NAME).getRange(range2).getValues();
values2_[0][0] = values2_[0][0].toString();
for(var i = 1; i < values2_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values2_[i][0] != "") {
values2_[0].push(values2_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM2_ID);
list.asListItem().setChoiceValues(values2_[0]);
}
function updateAdminTasks() {
var values3_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(AT_SHEET_NAME).getRange(range3).getValues();
values3_[0][0] = values3_[0][0].toString();
for(var i = 1; i < values3_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values3_[i][0] != "") {
values3_[0].push(values3_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM3_ID);
list.asListItem().setChoiceValues(values3_[0]);
}
function updateDesignTasks() {
var values4_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(DT_SHEET_NAME).getRange(range4).getValues();
values4_[0][0] = values4_[0][0].toString();
for(var i = 1; i < values4_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values4_[i][0] != "") {
values4_[0].push(values4_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM4_ID);
list.asListItem().setChoiceValues(values4_[0]);
}
function updateConstructionTasks() {
var values5_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(CT_SHEET_NAME).getRange(range5).getValues();
values5_[0][0] = values5_[0][0].toString();
for(var i = 1; i < values5_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values5_[i][0] != "") {
values5_[0].push(values5_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM5_ID);
list.asListItem().setChoiceValues(values5_[0]);
}
function updateHours() {
var values6_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(HOURS_SHEET_NAME).getRange(range6).getValues();
values6_[0][0] = values6_[0][0].toString();
for(var i = 1; i < values6_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values6_[i][0] != "") {
values6_[0].push(values6_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM6_ID);
list.asListItem().setChoiceValues(values6_[0]);
}
function getItemsOfForm(){
var form = FormApp.openById(FORM_ID);
var items = form.getItems(FormApp.ItemType.LIST);
for(var i in items){
Logger.log('id: ' + items[i].getId() + ' title: ' + items[i].getTitle());
}
}
PageBreakItem
A layout item that marks the start of a page. Items can be accessed or created from a Form.
PageNavigationType
An enum representing the supported types of page navigation. Page navigation types can be accessed from FormApp.PageNavigationType.
The page navigation occurs after the respondent completes a page that contains the option, and only if the respondent chose that option. If the respondent chose multiple options with page-navigation instructions on the same page, only the last navigation option has any effect. Page navigation also has no effect on the last page of a form.
Choices that use page navigation cannot be combined in the same item with choices that do not use page navigation.
// Create a form and add a new multiple-choice item and a page-break item.
var form = FormApp.create('Form Name');
var item = form.addMultipleChoiceItem();
var pageBreak = form.addPageBreakItem();
// Set some choices with go-to-page logic.
var rightChoice = item.createChoice('Vanilla', FormApp.PageNavigationType.SUBMIT);
var wrongChoice = item.createChoice('Chocolate', FormApp.PageNavigationType.RESTART);
// For GO_TO_PAGE, just pass in the page break item. For CONTINUE (normally the default), pass in
// CONTINUE explicitly because page navigation cannot be mixed with non-navigation choices.
var iffyChoice = item.createChoice('Peanut', pageBreak);
var otherChoice = item.createChoice('Strawberry', FormApp.PageNavigationType.CONTINUE);
item.setChoices([rightChoice, wrongChoice, iffyChoice, otherChoice]);
You can follow the sample create by Google and the implementation used in
Mogsdad's answert to further understand the flow.
I've added his code snippet:
function createForm() {
// Create a form and add a new multiple-choice item and a page-break item.
var form = FormApp.create('Form Name');
var item = form.addMultipleChoiceItem();
item.setTitle('Do you like Food')
var page2 = form.addPageBreakItem()
.setTitle('Page 2')
var item2 = form.addTextItem();
item2.setTitle('Why do you like food?')
var page3 = form.addPageBreakItem()
.setTitle('Page 3')
var item3 = form.addTextItem();
item3.setTitle("Why don't you like food?")
item.setTitle('Question')
.setChoices([
item.createChoice('Yes',page2),
item.createChoice('No',page3)
]);
}

Send pictures to a new window

I'm trying to make a slideshow of pictures and send them to an another window. But after selecting images and pressing the button for showing slideshows, nothing happens. I'm using firebug to detect bugs and when I'm going wrong. But I'm not getting any error from firebug so I gotta ask you guys. This is my code.
var infoBox;
var formTag;
var imgUrlList;
var imgTextList;
var windVar;
var urlList;
var textList;
function init() {
var i;
infoBox = document.getElementsByClassName("outerBox");
for (i=0; i<infoBox.length; i++) {
infoBox[i].onmouseover = showInfoBox;
infoBox[i].onmouseout = hideInfoBox;
}
formTag = document.getElementsByTagName("input");
for (i=0; i<formTag.length; i++) {
formTag[i].onclick = checkedBox;
}
windVar = null;
imgTextList = [];
imgUrlList = [];
}
window.onload = init;
function showInfoBox() {
var showInfo;
showInfo = this.getElementsByClassName("innerBox")[0];
showInfo.style.visibility = "visible";
}
function hideInfoBox() {
var hideInfo;
hideInfo = this.getElementsByClassName("innerBox")[0];
hideInfo.style.visibility = "hidden";
}
function checkedBox() {
var ImgNode, ImgTag;
for (i=0; i<formTag.length; i++) {
imgNode = this.parentNode.parentNode.firstChild;
imgTag = imgNode.nextSibling
if (this.checked) {
imgTag.className = "markedImg";
}
else {
imgTag.className = "unmarkedImg";
}
}
}
function slideShowBtn() {
var url, i, filename;
imgUrlList.length = 0;
imgTextList.length = 0;
for (i=0; i<formTag.length; i++) {
if (formTag.checked) {
url = infoBox.firstChild.getElementsByTagName("img")[i].src;
filename = infoBox.firstChild.getElementsByTagName("span")[i].src;
imgUrlList.push(url);
imgTextList.push(filename);
}
else break;
}
newWindow(700,600,"slideshow.htm");
}
function newWindow(width,height,fileName) {
var windProporties;
windProporties = "top=100, left=100,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height;
if (windVar != null) if (windVar.closed == false) windVar.close();
windVar = window.open(fileName,"bildspel",windProporties);
}
The formTag variabel is from a checkbox-input-tag. And it's from that I decide which pictures are selected and will be moved to the new page. ImgTextList and imgUrlList are global variables that'll also be in the next window. infoBox is a reference to a div class which is called OuterBox and inside it is an another div-class named innerBox, it's in the innerBox classdiv which the img and span-tags are. The code for the slideshow is already written and I'm just writing code for sending the variables to it.
Edit: I should have been a little more informative. But here's the code for the slideshow part where window.opener is present. And I've added all the remaining code that's above. How do you embed files?
// JavaScript for the slideshow page
// ----- Global variables -----
var imgUrlList = window.opener.imgUrlList; // Array with filenames of selected images. Initialized to an empty array.
var imgTextList = window.opener.imgTextList; // Array with image texts of selected images. Initialized to an empty array.
var slideshowMenu = null; // Reference to the image menu.
var slideshowImg = null; // Reference to the slideshow img tag.
var slideshowText = null; // Reference to the tag for the image text.
// ---- Create the image menu and show the first image. Also attach event handlers. ----
function initSlideshow() {
// Create a image list from the content of the variable imgUrlList
var HTMLcode = "<select id='imgMenu'>";
for (var i=0; i<imgTextList.length; i++) {
HTMLcode += "<option>" + imgTextList[i] + "</option>";
} // End for
HTMLcode += "</select>";
document.getElementById("iMenu").innerHTML = HTMLcode; // Add the select and option tags to the HTML code
slideshowMenu = document.getElementById("imgMenu"); // Save a reference to the menu's select tag
slideshowMenu.selectedIndex = 0; // Select the first option in the menu
slideshowImg = document.getElementById("slideshowBox").getElementsByTagName("img")[0];
slideshowText = document.getElementById("slideshowBox").getElementsByTagName("div")[0];
// Show the first image
slideshowImg.src = imgUrlList[0];
slideshowText.innerHTML = imgTextList[0];
// Attach event handlers
var slideshowButtons = document.getElementById("slideshowForm").getElementsByTagName("input");
slideshowButtons[0].onclick = showPrevImage;
slideshowButtons[1].onclick = showNextImage;
slideshowMenu.onchange = showSelectedImage;
} // End initSlideshow
window.onload = initSlideshow;
// ---- Show previous image in the list (menu) ----
function showPrevImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix > 0) { // If it's not already the first image
slideshowMenu.selectedIndex = ix-1;
slideshowImg.src = imgUrlList[ix-1];
slideshowText.innerHTML = imgTextList[ix-1];
}
} // End showPrevImage
// ---- Show next image in the list (menu) ----
function showNextImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix < slideshowMenu.length-1) { // If it's not already the last image
slideshowMenu.selectedIndex = ix+1;
slideshowImg.src = imgUrlList[ix+1];
slideshowText.innerHTML = imgTextList[ix+1];
}
} // End showNextImage
// ---- Show selected image in the list (menu) ----
function showSelectedImage() {
var ix = slideshowMenu.selectedIndex; // Index for the selected image
slideshowImg.src = imgUrlList[ix];
slideshowText.innerHTML = imgTextList[ix];
} // End showSelectedImage
Um, you never do anything to send it. Either pass it as a querystring parameter or have the child reference a global variable in the opener.
var foo = window.opener.imgUrlList;

Javascript reloading list each time event is fired - Google Drive Realtime API

I have a collaborative list in google's realtime api, which is displayed in a select tab.
Currently I have this.
var managment = (function($) {
var deadline1 = undefined;
// the name of the authenticated user - once authentication has succeeded
var username = "unkown";
var realtimeLoader = undefined;
var initializeModel = function(model) {
var deadline1 = model.createList();
model.getRoot().set('deadline1', deadline1);
}
var onProjectsLoaded = function(doc) {
deadline1 = doc.getModel().getRoot().get('deadline1');
deadline1.addEventListener(gapi.drive.realtime.EventType.VALUES_ADDED, updateUi);
deadline1.addEventListener(gapi.drive.realtime.EventType.VALUES_REMOVED, updateUi);
deadline1.addEventListener(gapi.drive.realtime.EventType.VALUES_SET, updateUi);
$("#inviteId").removeAttr("disabled");
var inviteButton = $("#invite");
inviteButton.removeAttr("disabled");
inviteButton.click(inviteUser);
var saveButton = $("#save");
saveButton.click(addProject);
var updateButton = $("#demoListSet");
updateButton.click(onSetItems);
var selector = $("#demoListInput");
selector.change(onSelect);
}
var addProject = function() {
var title = $("#title").val();
var date = $("#datepicker").val();
var priority = $("#priority").val();
var description = $("#description").val();
deadline1.push( {
title : title,
date : date,
description : description,
priority : priority,
} );
}
var updateUi = function(evt) {
/*$("#demoListInput").empty();*/
var projectList = $("#demoListInput");
for (var index in evt.values) {
var deadline1 = evt.values[index];
var newOption = $("<option>").val(deadline1.title).text("Title: " + deadline1.title + " Date:" + deadline1.date + " Priority: " + deadline1.priority)
}
projectList.append(newOption);
}
My problem is with the updateUI function.
The list is called deadline1. When an item is added to the list, it updates the list but the view of this list in the select tab, This is because I am only looping through the evt.values when displaying new items. What I would like to do it delete the current view of the list each time an event is fired (see the line currently in comment), however, every time I try and call deadline1 to loop through the length of it, it comes back saying deadline1 is undefined. Is there a way to get around this? Thank you.

Process multiple sharepoint list items

in a SharePoint list view I would like to duplicate selected list items. My code works when only one item selected but fails, when more. Debugging the code I see that it goes through all selected items first before calls the success callback. Also within the success callback the currItem not always filled with the item data.
How can I get and process the selected items one-by-one?
function copySelected(){
if($("#copyAllButton").hasClass('ms-cui-disabled')){
return;
}
var cc = null;
var web = null;
copyCounter = 0;
failedCounter = 0;
cc = new SP.ClientContext.get_current();
web = cc.get_web();
var currItem = null;
notifyId = SP.UI.Notify.addNotification(duplicatingItemsNotification, true);
var selectedItems;
currList = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList());
selectedItems = SP.ListOperation.Selection.getSelectedItems();
if( selectedItems.length > 0 ){
for(var i in selectedItems){
//var currItemID = selectedItems[i].id;
currItem = currList.getItemById(selectedItems[i].id);
cc.load(currItem);
cc.executeQueryAsync(function(sender, args){
var itemCreateInfo = new SP.ListItemCreationInformation();
var aListItem = currList.addItem(itemCreateInfo);
aListItem.set_item('Title', currItem.get_item('Title'));
aListItem.set_item('Customer', currItem.get_item('Customer'));
aListItem.set_item('Description', currItem.get_item('Description'));
aListItem.set_item('Source', currItem.get_item('Source'));
aListItem.set_item('field2', currItem.get_item('field2'));
aListItem.set_item('field3', currItem.get_item('field3'));
aListItem.set_item('Workloadtype', currItem.get_item('Workloadtype'));
aListItem.set_item('Tickettype', currItem.get_item('Tickettype'));
aListItem.set_item('Customergroup', currEngineer.group);
aListItem.set_item('Allocation', currEngineer.allocation);
aListItem.set_item('SubCap', currItem.get_item('SubCap'));
aListItem.set_item('Engineer', currEngineer.fullName);
aListItem.update();
cc.load(aListItem);
cc.executeQueryAsync(function(){
copyCounter ++;
},function(){
failedCounter ++;
});
}, Function.createDelegate(this,this.getItemFailed));
}
notifyMe();
}
}
In the meantime I found out the resolution (it was good to rethinking the problem for the question).
I fill an array of the required items with the query then processes the array.
var allSelectedItems;
function copySelected(){
if($("#copyAllButton").hasClass('ms-cui-disabled')){
return;
}
var cc = null;
var web = null;
copyCounter = 0;
failedCounter = 0;
cc = new SP.ClientContext.get_current();
web = cc.get_web();
//var currItem = null;
notifyId = SP.UI.Notify.addNotification(duplicatingItemsNotification, true);
var selectedItems;
currList = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList());
selectedItems = SP.ListOperation.Selection.getSelectedItems();
if( selectedItems.length > 0 ){
allSelectedItems = new Array(selectedItems.length);
for(var i in selectedItems){
allSelectedItems[i] = currList.getItemById(selectedItems[i].id);
cc.load(allSelectedItems[i]);
}
cc.executeQueryAsync(Function.createDelegate(this, this.getItemSucceded), Function.createDelegate(this, this.getItemFailed));
notifyMe();
}
}

Categories