How could I make it object-oriented - javascript

I have a js file which use Storage API. It just save form infos to get them if you have to fill the form again in a new session. It also re-use these infos to put them somewhere else in the page without page refreshing. It's working but I would like to make this in an object-oriented way.
Tried to learn OOP (beginner) and to make a function with the code which isn't in an object working at a window.onload event.
// STORAGE
// Used Elements
let input_textarea = document.querySelector('#firstname_area');
let input_textarea_bis = document.querySelector('#lastname_area');
let chosen_station = document.querySelector('#station')
let output_div = document.querySelector('.personal-greeting');
let output_station = document.querySelector('#custumerstation');
let save_button = document.querySelector('.send');
// Onclick start function
save_button.addEventListener('click', updateOutput);
// Saved Elements
output_div.textContent = localStorage.getItem('content');
input_textarea.value = localStorage.getItem('content');
input_textarea_bis.value = localStorage.getItem('contentbis');
chosen_station.innerHTML = sessionStorage.getItem('content');
// Function actions setting saved elements
function updateOutput() {
localStorage.setItem('content', input_textarea.value);
localStorage.setItem('contentbis', input_textarea_bis.value);
output_div.textContent = input_textarea.value;
output_station.textContent = chosen_station.innerHTML;
}

By creating a FormInformation class you could create attributes for the things you need to repeat elsewhere in your app like input text area fields, etc... This way, you could store an instance of FormInformation and set the attributes with the values of what you got while doing document.querySelector() and reuse it

Related

HTML and Native Javascript Change Iframe content based on search query

I've made a website that utilizes Bootstrap's tab navigation. For my blog, I have an iframe set into one of these tabs. I am currently trying to make it so that if I were to give someone a link with the query ?blogPost=a_post it would automatically redirect the SRC of the Iframe to /blog/a_post.html. I started by setting up the script to get the queries based on this article: https://www.sitepoint.com/get-url-parameters-with-javascript/. Then, I adapted the code to look like this:
function onload() {
let queryString = window.location.search;
let urlParams = new URLSearchParams(queryString);
if (urlParams.has('blogPost')) {
let blogPost = urlParams.get('blogPost');
document.getElementById('pills-home-tab').classList.remove('active');
document.getElementById('pills-blog-tab').classList.add('active');
document.getElementById("child-iframe").src = `./blog/${blogPost}.html`;
} else {
return;
}
}
window.onload = onload;
However, when I load the page https://website.com/?blogPost=welcome_to_my_blog none of the classList properties change, and the Iframe stays at /blog.html
I'm not sure where I'm going wrong, but I'm certain what I'm trying to do is possible, and under that assumption know I am at error in my code. No errors come up on my browser's console, either.
You declared a global function called onload, this has overwritten the native window.onload, making it not work. You can change the name of your function, or just add directly like this:
window.onload = () => {
let queryString = window.location.search;
let urlParams = new URLSearchParams(queryString);
if (urlParams.has("blogPost")) {
let blogPost = urlParams.get("blogPost");
document.getElementById("pills-home-tab").classList.remove("active");
document.getElementById("pills-blog-tab").classList.add("active");
document.getElementById("child-iframe").src = `./blog/${blogPost}.html`;
}
};

Adobe ExtendScript keep hyperlink page after changing document path

I'm trying to merge multiple Indesign documents and having problems with keeping the hyperlinks. The documents have external page hyperlinks and after merging I have to change the destination to the merged document. So I've created a little script that checks all hyperlinks and sets their documentPath to the current file. But the page from this hyperlink is lost after this. So I'm trying to save the page to a variable before changing the documentPath. But I can't set the destinationPageIndex with the variable. If I check the variable it has the right value, but setting it doesn't work, the hyperlink resets to page 1. If i just set destinationPageIndex = 20 for example it sets all links correctly. So it just ignores the page variable.
It seems like a simple problem but I seem to miss something.
var doc = app.activeDocument;
var hyperlinks = doc.hyperlinks;
for (i = 0; i < doc.hyperlinks.length; i++){
var hyperlink = hyperlinks[i];
var destination = hyperlink.destination;
if (destination instanceof HyperlinkExternalPageDestination) {
var page = destination.destinationPageIndex;
destination.documentPath = doc.fullName.absoluteURI;
destination.destinationPageIndex = page;
//destination.destinationPageIndex = 20;
}
}
As far as I can tell ExternalPageDestination destination doesn't work inside the document. You have to change the type of the destination to PageDestination if you want to make it work inside the current document.
Something like this:
var doc = app.activeDocument;
var hyperlinks = doc.hyperlinks;
var hyperlink = hyperlinks[0];
var destination = hyperlink.destination;
var page = destination.destinationPageIndex;
// create a new destination of the type 'PageDestination'
var new_destination = doc.hyperlinkPageDestinations.add();
// set the desired page
new_destination.destinationPage = doc.pages[page-1];
// assign the new destination
doc.hyperlinks[0].destination = new_destination;
// note: hyperlink.destination = new_destination; <-- won't work

Save spreadsheet row data to PDF using Gdoc template using Google Apps Script

I've exhausted all resources I'm aware of. Watched several different tutorials and spent many hours trying to make this code work.
I'm trying to automatically create a PDF from a spreadsheet row. I save copies of code at every successful run. However, I can't figure out at which point i'm triggering this error:
TypeError: Cannot read property 'makeCopy' of undefined (line 35, file "CreatePDF")
I was able to run the CreatePDF function successfully when defining the variables with "let" but since trying to pull them from the spreadsheet with the function: createbulkpdfs I haven't been able to progress.
Can anyone point me in the right direction? Line 35 noted below**
//doc id 1rFkh5AmLPNAJ7z1olWBvubn-6Oh8S8_my-AML1lU48I
//temp folder 12ZEXitbgdyOQJiC-pHvshgsBuNOKEKpj
//pdf folder 1eomwcc_UNJhFhvxcoWwamyJUterZtTaB
//let name = "Dan";
//let email = "daniel.sgalia#gmail.com";
//let cost = "100";
//let squarefeet = "2000";
//let flooringmaterial = "Wood";
//let roofingmaterial = "Standing Seam";
//let sidingmaterial = "Lap";
//let kitchencounter = "Granite";
function createbulkpdfs(){
const docfile = DriveApp.getFileById("1rFkh5AmLPNAJ7z1olWBvubn-6Oh8S8_my-AML1lU48I");
const tempfolder = DriveApp.getFolderById("12ZEXitbgdyOQJiC-pHvshgsBuNOKEKpj");
const pdffolder = DriveApp.getFolderById("1eomwcc_UNJhFhvxcoWwamyJUterZtTaB");
const currentsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SFR Calculations");
const data = currentsheet.getRange(2, 1,currentsheet.getLastRow()-1,15).getValues();
data.forEach(row => {
createPDF(row[0],email,cost,squarefeet,flooringmaterial,roofingmaterial,sidingmaterial,kitchencounter,pdfname,docfile,tempfolder,pdffolder)
});
}
function createPDF(name,email,cost,squarefeet,flooringmaterial,roofingmaterial,sidingmaterial,kitchencounter,pdfname,docfile,tempfolder,pdffolder) {
**LINE 35** const tempfile = docfile.makeCopy(tempfolder);
const tempdocfile =DocumentApp.openById(tempfile.getId());
const body = tempdocfile.getBody();
body.replaceText("{Name}", name);
body.replaceText("{Email}", email);
body.replaceText("{Cost Estimate}", cost);
body.replaceText("{Square Feet}", squarefeet);
body.replaceText("{Flooring Material}", flooringmaterial);
body.replaceText("{Roofing Material}", roofingmaterial);
body.replaceText("{Siding Material}", sidingmaterial);
body.replaceText("{Kitchen Counter}", kitchencounter);
tempdocfile.saveAndClose();
const pdfcontentblob = tempfile.getAs(MimeType.PDF);
pdffolder.createFile(pdfcontentblob).setName("pdfname");
tempfolder.removeFile(tempfile)
}
Not sure if you worked this out already, but I think the solution might be super simple...
Before you run the script, change it so you are running the function 'CreateBulkPDFs' not 'Create PDF'.
You have two functions in your script, you need to use the drop down at the top next to the Run button to ensure you are running the function 'CreateBulkPDFs'.
If you try to run 'Create PDF' the consts are not defined.
That error would throw because something isn't defined properly. At a glance it looks like because on line 35 you reference 'docfile' and 'tempfolder' which are not defined in the createPDF() function. (They are defined in the previous function)
It's not clear to be why you have the two functions and why you need createPDF to reference the other one, but it appears if you defined 'docfile' and 'tempfolder' (or any var or const that is needed in that function) within createPDF() specifically then it should run.
This should technically answer you question of why the error is happening on that line currently, without going into the full scope of needs for your project.

Get elements inside several html documents

I have a functionality in my system that transcripts from voice to text using an external library.
This is what the library renders:
What I need is really simple: to get the text from the generated textareas.
The textareas are rendered without any name or id, so I can only access them by class in the Google Chrome console. Whenever I try to get them by class in my javascript code, I get an array of [0] elements.
I think that the problem is that this library renders a new #document and I'm not able to get it's content in my $(document).ready function because it scopes the 'parent' document.
How it renders.
Any thoughts on this? Thank you.
I hope the code below helps.
// Get you iframe by Id or other way
let iframe = document.getElementById("myFrame");
// After iframe has been loaded
iframe.onload= function() {
// Get the element inside your iframe
// There are a lot of ways to do it
// It is good practice to store DOM objects in variables that start with $
let $elementByTag = iframe.contentWindow.document.getElementsByTagName("p")[0];
let $elementById = iframe.contentWindow.document.getElementById("elementId");
let $elementByClass = iframe.contentWindow.document.getElementsByClassName("classHere");
let $elementBySelector = iframe.contentWindow.document.querySelector("#dad .classname");
// After get the element extract the text/html
let text = $element.innerText
let html = $element.innerHTML
};

How to store created elements in Cookies or localStorage using javascript?

I dynamically create some a tags with JavaScript when clicking on other elements. When I refresh the page, the created elements disappear. Is there a way to store the creation of the elements in a JavaScript cookie?
function showTab(ev) {
let head = document.getElementById('heading');
let node = document.createElement("a");
node.classList.add("tab");
node.appendChild(document.createTextNode(ev.target.innerHTML));
head.appendChild(node);
};
Cookies are probably not the right way to go about something like this as there are size limitations
A better approach would be to store added elements inside the browser's localStorage or indexedDB. You can see an example of the latter in this simple todo app: http://todomvc.com/examples/react/#/
If you inspect the localStorage on that todo example after adding some items, you will see that there is an array containing your entries in JSON format.
Depending on what type of information you need to save, you could either save the HTML directly, or you could save JSON containing the relevant information (tab name, link URL, etc).
I would recommend against saving the HTML directly in case you ever need to make changes to the HTML on your site. Your users would then be loading up outdated HTML.
You can store outerHTML of created element in localStorage and get it on page load
var node = document.createElement("a");
node.classList.add("tab");
node.textContent = "new tag";
var local = localStorage.getItem("html");
if (local == null){
localStorage.setItem("html", node.outerHTML);
console.log('HTML setted in localStorage');
} else
console.log(local);
Because localStorage doesn't worked in snippet you should check it in jsfiddle
Note that if your html content is large you should consider max size of local storage
Okay, I solved it like that:
// Restore
window.onload = function() {
let head = document.getElementById('heading');
archive = [];
key = allStorage();
for(var i=0; i<archive.length; i++){
if(archive[i] != null){
let node = document.createElement("a");
node.classList.add("tab");
node.innerHTML = key[i];
head.appendChild(node);
}
}
}
//Store all
function allStorage() {
keys = Object.keys(localStorage); // Gibt alle Schlüssel zurück
archive = [];
for (var i=0; i< keys.length; i++) {
archive.push(keys[i]);
}
return archive;
}

Categories

Resources