"Updating" webpage through jQuery and localStorage - javascript

So I have a home page that I created using HTML. I run it off my computer by opening the HTML file. I'm trying to add a feature that allows me to edit it from the page (using content-editable or append), not the source code. To achieve this, I came up with using localStorage to hold the updated version of the webpage, and loading the page from that updated version. See here. (Theoretically, I would periodically update the source code from the localStorage version so it's all matched up.)
However, when I tried it, my page won't update. I have a version saved into localStorage, but it seems as if the program can't overwrite the that version, or something similar.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>SCSS | Projects</title>
<link type="text/css" rel="stylesheet" href="home page heading style.css">
<link type="text/css" rel="stylesheet" href="home page projects style.css">
<script type="text/javascript" src="save script.js"></script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body onload="checkEdits()">
<div id="everything">
<div class="box">
<div class="img"><img src="who am i.png" /></div>
<div class="wrapper">
<div class="title">Who Am I?</div>
<div class="description">A project for English class describing who I am through different medias and explained by unit questions.</div>
</div>
<div class="notes" contenteditable="true">Complete.</div>
</div>
S
</div><!--End everything-->
</body>
My JavaScript looks like this:
function saveEdits() {
//get the editable element
var edited = document.getElementById("everything");
//get the edited element content
var userVersion = edited.innerHTML;
//save the content to local storage
var localStorage.Edits = userVersion;
}
function checkEdits() {
//find out if the user has previously saved edits
if(localStorage.Edits != null)
document.getElementById("everything").innerHTML = localStorage.Edits;
}
But my page doesn't actually work right; it doesn't load the updated version. From viewing localStorage, it seems as if it's not even saving it properly.
Why doesn't it work? How can I fix it? Is there something conceptually incorrect about my plan? Any help would be appreciated; thanks!

For localStorage you can get/setItem e.g.
function saveEdits() {
//get the editable element
var edited = document.getElementById("everything");
//get the edited element content
var userVersion = edited.innerHTML;
//save the content to local storage
localStorage.setItem('Edits', userVersion);
}
function checkEdits() {
//find out if the user has previously saved edits
var savedEdits = localStorage.getItem('Edits');
if (savedEdits != null) {
document.getElementById("everything").innerHTML = savedEdits;
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Storage
You might also notice that jQuery is not used/required for this code...

Related

Prevent browser from partially rendering the page while the document is being loaded [duplicate]

This question already has answers here:
How can I make the browser wait to display the page until it's fully loaded?
(16 answers)
Closed 4 years ago.
Both Firefox and Chrome is rendering my pages way too early, which results in my a couple of frames where you first see the header, then the content, and then the footer. It's a very very unpleasant page loading experience.
The way I get around this right now is this, which is such a silly workaround I would like to avoid. It also causes the page to flash white in Chrome.
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<div id="render-all-at-once" style="opacity:0; min-height:100%;">
content
</div>
<script>
document.getElementById("render-all-at-once").style.opacity = 1;
</script>
</body>
</html>
The problem is basically this:
<script>
function sleep(millis) {
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while (curDate - date < millis);
}
</script>
<div>
This will be rendered in the first frame.
</div>
<script>
sleep(3000);
</script>
<div>
And only after that first frame has been rendered will you see this line. You don't see the first line for 3 seconds as
you might, but you do see it flash, right before both lines are displayed.
</div>
<!---
I would like the browser to not render anything until
the entire entire document has been processed.
--->
In isolated tests, the above code seem to work as expected - both lines will be rendered at the same time after 3 seconds. But as soon I start adding a couple of random style-sheets to the page, the problem starts occurring.
I can't seem to narrow it down to any particular style-sheet or style. I can't figure out what's causing it. I've both tried loading all styles sheets from , or just having all of them inlined in a style element. This doesn't make any difference. I'm testing this using Chrome as it seems to happen more frequently there.
Does anyone have any experience with this sort of problem, or have any ideas what's causing it, and know of any way to prevent it?
What I like to do is wrap my content in a div and set it to display:none.
Then, I defer my CSS loading and in my CSS file, and set that wrap div to display:block.
I also compress all my CSS files into one single file (for better loading).
<!DOCTYPE html>
<html>
<head>
<style>
.wrap {
display: none;
}
</style>
</head>
<body>
<div class="wrap">
content
</div>
<noscript id="deferred-styles">
<link rel="stylesheet" type="text/css" href="compressed.css" />
</noscript>
<script>
var loadDeferredStyles = function() {
var addStylesNode = document.getElementById("deferred-styles");
var replacement = document.createElement("div");
replacement.innerHTML = addStylesNode.textContent;
document.body.appendChild(replacement);
addStylesNode.parentElement.removeChild(addStylesNode);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if(raf) {
raf(function() {
window.setTimeout(loadDeferredStyles, 0);
});
} else {
window.addEventListener('load', loadDeferredStyles);
}
</script>
</body>
</html>
Use the network tab in developer tools to see the process & response of each request. First, the HTML is fully received and parsed by the browser which then looks for remote objects to load top-down: stylesheets, images, javascript, etc.
So, to have complete control over how things appear, send an HTML document that looks exactly as you'd like the initial view to be (ex: a blank white document, achieved with inline CSS or a <style> tag that targets <body>). Then use a line of Javascript to listen for the load event and update your display, for example:
<!doctype html>
<html>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/stackoverflow/primary.css">
<body style="display: none;">
<h1>Headline</h1>
</body>
<script>
window.addEventListener("load", function(event) {
document.querySelector("body").style.display = "block";
});
</script>
</html>

Unable to trigger onmouseenter events?

I was able to make onmousesenter work correctly when I included the reference to the function directly in the html, but read that was bad form and wanted to improve my code- but now I can't get it to run, despite my code showing it does trigger the function, I'm just not sure why the rest of it fails to run now:
<DOCTYPE! html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<title>Sexism in Silicon Valley</title>
<script src="index.js"></script>
</head>
<body id="body1">
<div class="parent">
<img src="kstartup.png" class="logos" id="id1"></img>
<img src="uber.png" class="logos" id="id2"></img>
<img src="kpcb.png" class="logos" id="id3"></img>
<img id="id4" src="r1startup.png" class="logos"></img>
</div>
Javascript (index.js):
function mouseenter() {
alert("hey");
var z = document.getElementsByClassName("parent");
for (var i = 0; i < z.length; i++) {
z[i].style.background = "black";
}
var bod = document.getElementById("body1");
bod.style.background = "black";
}
document.getElementById("id1").onmouseenter = mouseenter();
The alert goes off as soon as I load the page instead of when my mouse enters the id1. Why isn't it triggered by my mouse entering the id?
Your document DOM is not ready when you try to access the ID id1 Element.
document.getElementById("id1").onmouseenter = mouseenter; // Don't execute()
// Since this code is inside HEAD, JS does not know about any #id1 Element yet.
cause you're calling the <script> tag inside <head> instead of at the bottom before the closing </body> tag.
<script src="index.js"></script> <!-- Makes sure parser readed all the elements -->
</body>
</html>
document.getElementById("id1").onmouseenter = mouseenter; // << no ()
// Assign, don't execute.
There are quite a number of issues here:
The doctype is incorrect
Image tags do not have a closing equivalent in HTML5, i.e. </img> does not exist (was a thing in XHTML)
You have not wrapped you JavaScript in <script> tags so it is being interpreted as HTML
You are calling the mouseenter function when you are assigning it, so you actually assigning the result. In other words you should just assign a reference to the function: document.getElementById("id1").onmouseenter = mouseenter
Working example here: http://plnkr.co/edit/fmBIM7U6QSS0cl7vqdlQ?p=preview (obviously the images will not load, as you only provided relative paths)

printing contents in a new tab prints a blank page

I am trying to print the contents of a div to a new tab, however, it print a blank page only for the first time. When i manually print the page, it works fine. I am loading 2 tables wrapped in a div.
HTML structure:
<div class="receipt_bg" id="print_receipt">
<div id="div1">
table1
</div>
<div id="div2">
table2
</div>
</div>
<button type="button" id="print_btn">Print</button>
Javascript:
$('#print_btn').click(printClick);
function printClick(receipt_bg) {
var DocumentContainer = $('.receipt_bg').html();
var WindowObject = window.open("PrintWindow","_blank");
WindowObject.document.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">'+ '<html><head><title>test print receipt</title> <link href="../css/style.defaultprint.css" rel="stylesheet" type="text/css" /></head><body>' + DocumentContainer + '</body></html>')
setTimeout(WindowObject.print(), 5);
WindowObject.close();
}
I even tried using
WindowObject.onload = WindowObject.print();
instead of
setTimeout(WindowObject.print(), 5);
still it doesn't seem to work. I saw a similar post, but its solutions did not work for me.
Check this url.
It contain few example for printing content from page.It has all you need.
I had use jQuery Print Element 1.2 for print, in this, if you have large content to print then you need to increases time out from 50 to 500,other wise it will show blank page as you face issue, but for me it is only happend in Chrome browser, other then that i haven't face this issue.
check printElement js. below url contain nice example with demo and source.
Check this : jQuery Print Page Options
Here is the code , which will help you.
function printClick(receipt_bg) {
var DocumentContainer = $('.receipt_bg').html();
var WindowObject = window.open("", "printElementWindow", "width=650,height=440,scrollbars=yes");
WindowObject.document.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">'+ '<html><head><title>test print receipt</title> <link href="../css/style.defaultprint.css" rel="stylesheet" type="text/css" /></head><body>' + DocumentContainer + '</body><script type="text/javascript">setTimeout(printPage(),1000); function printPage(){focus();print();}<\/script></html>')
WindowObject.close();
}
This will work for you, here i added one javascript function to your window code, which will executed after timeout. try it, and let me know , is it work for you or not. you can extend or decrees timeout as per your content.

HTML Passing Values between pages in different locations

I am needing to open an html page on server-A and grab some values from server-B's webpage. In other words I want to display server-B's webpage values on server-A's webpage.
The webpage (server-B) data I need the values from is being populated by a source that I do not have access. The values are written into what appears to be a variable that looks like this: [[0]]. When the page is accessed that value [[0]] is populated with current data.
I have unsuccessfully tried to attach a label to the [[0]] to allow reading from server-A with a form post and get methods.
What should my approach be to move this data in [[0]] to server-A webpage?
Server-B page:
<html>
<!-- Head information for the page including page title -->
<head>
<title>Test</title>
</head>
<body color=#FFFFFF>
<!-- Start of your page body -->
<!-- This code displays the current tag value for index 0
[[0]] will be replaced by the tag value a the time the page is loaded -->
The value of the tag with index 0 is [[0]]
<!-- Added code to store [[0]] in div -->
<div class="pink-box" id="thatDiv">[[0]]</div>
</body>
</html>
I added this html/javascript for Server-A and I am getting the an error described with COR:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Div</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<b>Div:</b>
<ol id="Result"></ol>
<script>
$("#Result").load("http://192.168.1.168/user/default.html #thatDiv");
</script>
</body>
</html>
You can get the contents of the HTML file and find the starting "[[" and the ending "]]" and grab the data in between.
<?php
$serverBFile = "http://www.serverB.com/file.html";
$serverBHTML = file_get_contents($serverBFile);
$serverBStart = stripos($serverBHTML,"[[");
$serverBEnd = stripos($serverBHTML,"]]");
$serverBLength = $serverBEnd - $serverBStart;
$serverBValue = substr($serverBHTML, $serverBStart, $serverBLength);
?>
The way that I have done this in the past is using DOM parsing tools like jQuery.
If you have access to a node.js server, you can use the jQuery plugin to load up server-B's webpage and then query something that's constant with the desired tag, be it ID, classname, tagname, location, etc.
<html>
<!-- Head information for the page including page title -->
<head>
<title>Test</title>
</head>
<body color=#FFFFFF>
<!-- Start of your page body -->
<!-- This code displays the current tag value for index 0
[[0]] will be replaced by the tag value a the time the page is loaded
let's say [[0]] becomes a <div>-->
<div class="pink-box" id="thatDiv">data I want</div>
</body>
</html>
From here, it's fairly easy to extract the text via $('#thatDiv').text() or $('.pink-box').text().
This is a fairly simple solution. Once you get that value into a variable in your node server, just expose a REST call that your server-a webpage can make an AJAX request to.
The reason I say to use node is because it seems that this page has dynamic content that must be loaded with JavaScript. If I knew more about how this page interacted, I would be able to give more specific solutions to your problem,

Changing colour of borderBottom on top location address

I'm making a very basic menu for my site and I have used the border-bottom property to underline the items. What I want is to highlight the underline pink if you're on a certain page. I've used custom "url" elements and "link" attributes. I would like it so if the user is on page1 the page1 item would underline pink. Here's what I've tried so far:
<script>
function col(){if(top.location.href==document.getElementsByTagName("url")[1].link){this.style.borderBottom="solid #F05";};}
</script>
^ That was completely wrong, I was testing with a bit of code from W3Schools.
I also tried:
<script>
function menuCol(url){if(top.location == url){this.style.borderBottom="solid #F05";};}
</script>
^ This one worked but I had to include "[PAGE NO]" on every page so the script could match the IDs of the page and URL element.
Does anyone know how I can actually make this work without having to put in pageID tags in?
----- Edit -----
Sorry, I'm not exactly sure how to put the problem into words but here's the page and source code (currently):
http://3659905.webs.com/ExternalPages/Desktop/Menubar_test.htm
<head>
<title>Menu</title>
<noframes></noframes><noscript></noscript><!-- --><script type="text/javascript" src="http://www.freewebs.com/p.js"></script><script></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="JavaScript" src="http://images.freewebs.com/JS/Freebar/bar_sidegrey.js"></script>
<script>
$(document).ready(function(){
$("url").click(function(){
top.location.href="http://"+$(this).attr("link")
});
});
</script>
<script>
function col(){if(top.location.href==document.getElementsByTagName("url")[1].link){this.style.borderBottom="solid #F05";};}
</script>
<style>
url{text-decoration:none;font-size:15px;padding:3px;border-bottom:solid #AAA;}
url:hover{cursor:pointer;border-bottom:solid #FFF}
body{background:black;color:white;font-family:arial;cursor:default;}
</style>
</head>
<body onselectstart="return false;" oncontextmenu="return false;" onload="col();">
<center>
<url link="3s.uk.to">Home</url>
<url link="3apps.uk.to">App Store</url>
<url link="3659905.webs.com/ExternalPages/Desktop/Menubar_test.htm">Menu Test</url>
</center>
</body>
The best guess I could make, given the sparsity of information in the question, is this:
// in real life, use:
// var url = window.location;
var url = "http://some.domain.com/index.html";
function markActive(elem) {
if (url.indexOf(elem.href.split('/').pop()) > -1) {
return 'active'
}
}
var as = document.getElementsByTagName('a');
for (var i=0,len=as.length; i<len; i++){
as[i].className = markActive(as[i]);
}​
JS Fiddle demo.
This, in its current incarnation, works only for the name of the page, so if you had multiple index.html pages, albeit in different directories, they would all assign the active class (if you were currently in www.example.com/index.html).
As they said, we need more code.
But if you want to take the current "pagename" and get the links containing that page you could do this:
//get current adress
var URL = window.location.pathname;
//get the filename with extension
var PageName = URL.substring(URL.lastIndexOf('/') + 1);
//use jquery to find links pointing to the file
$('#YOURMENU a[href='+PageName+']').css("border-bottom-color", "#F05");

Categories

Resources