Copy HTML Table to localStorage - javascript

I have a table that is being generated automatically through the javascript application.
See test site here: https://hhpricetools.com/3d-wood-designer/
The summary table is on the last tab or you can click "view summary" at the top to get to it.
The table that is populated based on user choices looks like this:
<table id="summary-table" class="hhpt-summarytable"><tbody>
<tr><td>Style: <b>Side Lofted Barn</b></td>
<td> </td></tr>
<tr><td>Size: <b>10' x 16'</b></td><td> </td></tr>
<tr><td>Siding: <b>LP Smartside - Painted</b></td><td> </td></tr>
<tr><td>Wall Color: <b>Quest Gray #7080</b></td><td> </td></tr>
<tr><td>Trim Color: <b>White</b></td><td> </td></tr>
<tr><td>Roof: <b>Radiant Barrier LP Techshield</b></td><td> </td></tr><tr><td>
</td></tr></tbody></table>
That I am wanting to save to localStorage. For some reason I am getting "undefined" on the actual website above. The jsfiddle works fine, though. Why isn't it doing the same on the website?
var table_copy = $('#summary-table').html();
localStorage.setItem('table',table_copy);
console.log(localStorage.getItem("table"));
https://jsfiddle.net/ebryjz1q/

There are a few methods that you can do to make sure that your JavaScript loads after the DOM/HTML loads.
1. Use defer
You can use defer to load the JavaScript after the HTML has loaded.
To do this, you can simply add the following attribute.
<script defer src="index.js"></script>
This should wait until the DOM has loaded before actually loading the JavaScript.
2. Add <script> to <body>
Another solution is to add the script tag to the end of the body. This will make the JavaScript code load after all of the HTML has loaded.
3. Wait in JavaScript
You can also wait for the DOM to load in JavaScript (without JQuery).
There are two methods.
You can use the DOMContentLoaded event listener. This will wait until the HTML has loaded. However, it won't wait for the images to load, stylesheets, etc.
To use this, you can use addEventListener().
window.addEventListener("DOMContentLoaded", () => {
// Code here will execute only after the DOM has loaded...
});
You can also use the load event, which will load after the HTML has loaded, as well as images, stylesheets, etc.
You can use this listener with addEventListener too.
window.addEventListener("load", () => {
// Code here will execute after everything has loaded...
});
You can do the same thing with the onload event handler property.
window.onload = () => {
// Code here will execute after everything has loaded...
};
In conclusion, there are many ways to make the JavaScript wait until the DOM has loaded.

You need to ensure the DOM has fully loaded before trying to store the HTML.
Try the following:
$('document').ready(function() {
var table_copy = $('#summary-table').html();
localStorage.setItem('table',table_copy);
console.log(localStorage.getItem("table"));
});

Related

getElementById/InnerHTML Function not Working

I'm playing around with Javascript to get back in the swing of things for my second semester web class that recently started, and I've run into an issue getting getElementById and innerHTML to work.
Basically, I want to populate an empty h1 with an Animal name
function favAnimal()
{
document.getElementById("animal").innerHTML="cat"
}
<h1 id="animal" onload="favAnimal()">Favourite Animal Placeholder</h1>
The above does not change anything. If the h1 is empty the result is the same. I've also tried with a <div> to rule out an issue using specific elements.
All help is appreciated and thanks in advance!
An <h1> tag does not have an onload event handler so your function is never being called.
You can use the onload handler for the <body> tag or set up some other event handler to assign your function to.
If you want your code to be triggered when the document is loaded, you can use one of these:
window.addEventListener("load", favAnimal); // all page resources loaded
document.addEventListener("DOMContentLoaded", favAnimal); // HTML done parsing
If you just want your script to be executed right after your <h1> tag has been loaded, you can just place a call to the script right after the tag. The page is parsed/executed in order so that any script will always be able to reference HTML elements that come before it in the document:
<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>
Here are some of the things I'm aware of that have a load event:
window
<img>
<body>
<iframe>
<link>
<script>
<embed>
<object>
<video>
<audio>
XMLHttpRequest
And, pretty much any other HTML tag that has a src or href attribute except <a>. The idea is that if the tag is loading some external resource, then there is a load event to know when it is done loading that external resource. If the tag is not loading an external resource, there is probably not a load event for it.
The load event is only dispatched on resources, such as the document, images, ...
If you want to run some script just after an element has been parsed, just add a script element after it:
<script>
function favAnimal() {
document.getElementById("animal").innerHTML = "cat";
}
</script>
<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>
What is happening here that ur script file executed earlier than the html renders. So it is not able to locate the element as it is not rendered yet. Browser provides events like onload ,unload. Here u need onload
`Document.addEventListener("DOMContentLoaded",init);
Function init (){
//ur code
}`

Is there a way to load doubleclick.net ad tags on document.ready?

I tried to load doubleclick.net ad tags on document.ready, but the ads don't show up.
HTML
<script language="JavaScript" type="text/javascript" data-ad-src="http://ad.ch.doubleclick.net/adj/swisswebcams/;lng=de;kw=home;tile=3;dcopt=ist;sz=160x600;ord=1874680027?"></script>
JavaScript (requires jQuery)
$(document).ready(function(){
$('script[data-ad-src]').each(function(){
this.src = $(this).attr('data-ad-src');
$(this).removeAttr('data-ad-src');
});
});
The script shows up correct in the generated source code, but it doesn't load the ads anymore. Does the script require the document.ready event? Is there maybe a way to load this script just before document.ready - or to trigger document.ready again?
PS: I prefer to use the "sync" tags over the "async" tags, because "async" is creating an iFrame which then is not flexible in width/height anymore when showing 3rd party networks dynamically.
Try this
<script>
var wr = document.write, dchtml=[];
document.write=function(str) {
// you may want to catch '<script' and add the src to the head when needed
dchtml.push(str);
}
</script>
<script language="JavaScript" type="text/javascript" data-ad-src="http://ad.ch.doubleclick.net/adj/swisswebcams/;lng=de;kw=home;tile=3;dcopt=ist;sz=160x600;ord=1874680027?"></script>
<script>
$(function() { // assuming jQuery is loaded before this block
$("#whereIWantMyAds").html(dchtml.join("\n"));
});
<script>
Check your JavaScript errors. Most likely this is a problem with asynchronous downloading of the script, in fact: I'm sure. This is in the script from doubleclick (downloaded from the link you provided:
document.write('\x3cdiv...
a document.write doesn't work since document.ready already closed the document DOM. You specifically need to add the code to an element in your DOM, which can't be done with document.write. In order to make this work you have to either contact doubleclick and make them change every document.write to something that attaches the code to an element in your page, or asynchronously load the code (including the script) in an iframe.

Javascript adding <script> tag after page loads

Got a little problem here. Basically, I'm trying to add a script tag after the page loads.
This is what I am doing:
index.php:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getad()
{
$.post('assets/getad.php', "ad", function(response) {
response = response.replace('document.write','document.getElementById("ad").innerHTML = ');
eval(response);
console.log(response);
});
}
getad();
</script>
<div id="ad"></div>
</body>
</html>
getad.php:
<?php
echo file_get_contents("http://ads1.qadabra.com/t?id=a823aca3-9e3c-4ddd-a0cc-14b497cad85b&size=300x250");
?>
You can find a demo here: http://dev.cj.gy/game/
As you can see, the #ad div DOES get filled with the correct script tag, but it doesnt actually run, If I edit the page to include the script tag right at page load, it does run.
Yes, <script> tags cause execution when parsed as part of the main document; they don't execute from being written to innerHTML.
You can create an executing script element outside of that initial parse using the DOM method of calling createElement('script'), setting its src/content and adding it to the document. This is what jQuery's getScript does.
However it wouldn't do you much good because the next script, that ads1.qadabra.com is document.writeing to the page, also itself calls document.write.
You could work your way around both of these calls at the client side (ie without getad.php), by assigning your own custom function to document.write that, instead of writing to the loading page, attempts to extract the source of the script tag passed to it, and load that in a DOM-created script element.
But in general these are scripts designed to work synchronously at document load time; anything you do to try to force them to run in a way they weren't intended to is likely to be fragile and stop working when the ad network change anything.
If you want to load a third-party ad without pausing the loading of the parent document, I suggest putting it in an iframe.

Re-serving a sites javascript dynamically

I would like to dynamically load a javascript file and undo what was done with the static javascript i have on my site. the static javascript i want to edit is
document.getElementsByTagName('script')[3]this is what im trying to do:
document.getElementsByTagName('script')[3].attributes[2].value = "http://differentlocation.com/jsfile.js"
The thing is when the source is altered I want all the other functions i had statically cached to go away. how is this possible?
*reworded. The sites current javascript attaches event handlers and does all kinds of functions, i would like to make all of these go away. Basically I am reloading a Almost exact copy of the javascript and dont want certain handlers active. etc
Or is there a way to blank out all of the pages current javascript, Just make it all useless, and then Load my new javascript
It looks like you're not using jQuery. If you were, this simple line of code should remove all event handlers from every element in your document:
$("*").off();
It might be worth exploring.
I'm unable to get the JavaScript to run again, most likely: it needs to be linked (which jsFiddle doesn't allow). Here's a demo.
In this example, we have three buttons.
<button id="myButton">Add an event listener for the bellow</button>
<button id="listener">Do something</button>
<button id="reset">reset</button>
We can then add event listeners,
// Do some stuff
document.getElementById("myButton").addEventListener("click", function () {
document.getElementById("listener").addEventListener("click", function () {
alert("I do something!");
});
});
... and at some point, reset the page. This works by taking the current HTML content out of the page, and having it stored in a variable. We then put it back in, causing all bindings to elements to be removed. It also has the harmful side effect of not running inline scripts.
// Soft reload of the page
document.getElementById("reset").addEventListener("click", function () {
var html = document.documentElement.innerHTML;
document.documentElement.innerHTML = "";
document.documentElement.innerHTML = html;
});

Difference between onload() and $.ready?

Can you list the difference between onload() and $(document).ready(function(){..}) functions in the using jQuery?
the load event (a.k.a "onload") on the window and/or body element will fire once all the content of the page has been loaded -- this includes all images, scripts, etc... everything.
In contrast, jquery's $(document).ready(...) function will use a browser-specific mechanism to ensure that your handler is called as soon as possible after the HTML/XML dom is loaded and accessible. This is the earliest point in the page load process where you can safely run script that intends to access elements in the page's html dom. This point arrives earlier (often much earlier) than the final load event, because of the additional time required to load secondary resources (like images, and such).
The main differences between the two are:
Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document.ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded. Hence, the functions in jQuery's ready event will get executed once the HTML structure is loaded without waiting for the resources.
We can have multiple document.ready() in a page but Body.Onload() event cannot.
Document.ready() function triggers as soon as HTML DOM loaded. But the onload() function will trigger after HTML DOM, all the body content like images loaded.
body.onload() cares about both HTML structure and assoicated resources where as document.ready() cares only about the HTML structure.
onload() fires when all the content (everything) on the targeted eleement is fully loaded like CSS, images etc.
$.ready indicates that code in it need to be executed once the targeted elements content loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
.
Ex(body onload):
<body onload="loadBody()">
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body
Ex(onload on an element):
<img src="w3html.gif" onload="loadImg()" width="100" height="132">
<script>
function loadImg() {
alert("Image is loaded");
}
</script>
Ex3 ($.ready):
<script type = "text/javascript">
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
Onload take care about DOM and resources: it checks if images are loaded, script are ready to run and much more.
$.ready simply check if we have read the full DOM of the page.
Please check out this link for more explain and example: http://dailygit.com/difference-between-document-ready-and-window-load-in-jquery/

Categories