How to reload page without losing any inserted (div) data - javascript

i have multiple tags, which is set as editable (contentEditable="true"). is there any way to store contents in divs before load and paste the same after reload or any alternative way to do this?. I am very new in the programming field
<div contentEditable="true" id="main" key="main" class="main" >
<div contentEditable="true" id="div1" onfocusout="myFunction()"><p>sample para</p></div>
<div contentEditable="true" id="div2" onfocusout="myFunction()"><p>sample para</p></div>
</div >
window.onload = function()
{
var a = sessionStorage.getItem('main');
//alert(a);
document.getElementById("main").value = a;
}
window.onbeforeunload = function() {
sessionStorage.setItem("main", $('#main').val());
}
I tried this, but it is only for forms with known input field
My body html looks like
<body>
<div>Math in TeX notation</div>
<div contentEditable="true" id="main" key="main" class="main" >
<div contentEditable="true" id="div1" onfocusout="myFunction()"><p>sample para</p></div>
<div contentEditable="true" id="div2" onfocusout="myFunction()"><p>sample para</p></div>
</div>
</body>

You can save any data to session storage and use it later with JavaScript:
window.onload = function () {
const content = sessionStorage.getItem('main');
if (content) {
document.getElementById("main").innerHTML = content;
}
}
window.onbeforeunload = function () {
sessionStorage.setItem("main", document.getElementById("main").innerHTML);
}

I hacked this together, it works for me (using Firefox), i tested it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="memo-pad">
<pre id="memo" contenteditable="true" onkeyup="storeUserMemo(this.id);"></pre>
</div>
<script>
function storeUserMemo(id) {
let memo = document.getElementById("memo").innerHTML;
localStorage.setItem("userMemo", memo);
}
function getUserMemo() {
let memo;
if (localStorage.getItem("userMemo")) {
memo = localStorage.getItem("userMemo");
} else {
memo = "Please write something here!";
}
document.getElementById("memo").innerHTML = memo;
}
function clearLocal() {
localStorage.clear();
document.getElementById("memo").innerHTML = "Please write something here!";
}
getUserMemo();
let memo = document.getElementById("memo");
memo.addEventListener("input", function () {
console.log("Wer ändert hier sein Memo?")
});
</script>
</body>
</html>
Whatever you put in there survives the page reload now.

Related

coloring in grid blocks in JS

New to JS. Im trying to get my color button and other buttons working, where on clicking the color button, the grid blocks will be colored in black after mouseover. I'm trying to add eventlisteners in the play function to change the backgroundcolor of gridSquare, but can't because of the scope. How would i go about doing this?
JS
const colorBtn = document.getElementById('color')
const eraseBtn = document.getElementById('erase')
const clearBtn = document.getElementById('clear')
const gridCont = document.getElementById('grid')
let currentMode = ''
// creates grid on pageload
function makeGrid() {
for (i=0; i<1600; i++) {
let gridSquare = document.createElement('div')
gridCont.appendChild(gridSquare)
gridSquare.classList.add('gridSquare')
}
}
window.onload = makeGrid()
//
colorBtn.addEventListener('click', () => {
currentMode = 'color'
})
eraseBtn.addEventListener('click', () => {
currentMode = 'erase'
})
clearBtn.addEventListener('click', () => {
currentMode === 'clear'
})
function play() {
if (currentMode === 'color') {
}
}
window.onload = play()
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>scribblyscrabblydoo</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<div class="titlebox">
<h1>sribblyscrabblydoo</h1>
<p>Draw or something idk bro</p>
</div>
<div class="mainbod">
<div class="options">
<div class="buttons">
<h2>Options</h2>
</div>
<div class="buttons">
<button id="color">Color</button>
</div>
<div class="buttons">
<button id="erase">Erase</button></div>
<div class="buttons">
<button id="clear">Clear</button>
</div>
<div class="buttons">
<button id="github">Duskope Github</button>
</div>
</div>
<div id="grid"></div>
</div>
</body>
<script type="text/javascript" src = "index.js"></script>
</html>
https://duskope.github.io/scribblyscrabblydoo/
To solve the background color issue, its actually just a typo.
Change your play function to this
Fyi, you're gonna run into another issue of it making EVERYTHING black. So add some conditionals.
function play() {
document.querySelectorAll('.gridSquare').forEach((item) => {
addEventListener('mouseover', (e) => {
e.target.style.backgroundColor = 'black'
})
})
}

How should I make input permanent and make the input stay even after reloading the page in html? [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 1 year ago.
How should I make input permanent? Like for example, if I type in "Hello world" it should say "hello world " and "hello world" should be there even after reloading
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="content"></p>
<input type="text" id="userInput">
<script>
function getInputFromTextBox() {
let input = document.getElementById("userInput").value;
document.getElementById("content").innerHTML = input;
}
</script>
<button onclick="getInputFromTextBox()">submit</button>
</body>
</html>
You can use localStorage
// JAVASCRIPT
// Getting the value from localStorage
// The "key" here need to be the same defined below on the save() function
const getValue = localStorage.getItem("key");
if (getValue) {
document.getElementById("inputId").value = getValue;
}
function save() {
const setValue = document.getElementById("inputId").value;
// Here you can set 'key' with any name you like
// Setting the value in localStorage
localStorage.setItem("key", setValue);
}
<!-- HTML -->
<input type="text" id="inputId" />
<button onclick="save()">save value</button>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3>Type here</h3>
<input type="text" id="inputText">
<input type="submit" id="submit">
<p id="seeHere"></p>
</body>
<script>
if(localStorage.getItem("info")==null){
}
else{
value();
}
let submit = document.getElementById("submit");
submit.addEventListener("click", function () {
console.log("hello world");
let inputText = document.getElementById("inputText");
let inputTextvalue = inputText.value;
inputText.value="";
let localValue = localStorage.getItem("info");
if (localValue == null) {
arr = [];
}
else {
arr = JSON.parse(localValue);
}
arr.push(inputTextvalue);
localStorage.setItem("info", JSON.stringify(arr));
value();
})
function value() {
let localValue = localStorage.getItem("info");
let seeHere = document.getElementById("seeHere");
seeHere.innerHTML="";
let seeHeretext="";
let parsedLocalvalue= JSON.parse(localValue);
parsedLocalvalue.forEach(element => {
seeHeretext=seeHeretext+`${element}<br>`;
});
seeHere.innerHTML=seeHeretext;
}
</script>
</html>
This is the required answer for the question see carefully .

When I rendering my template I would like to display a function of eventHandler

I made a templating with handlebars, so now my problem is simple :
When user put a letter or words or something else in the input field, the function launch the ajax call and he return the result.
But, I think, I took the problem upside down.
So if you would like to help me, you can check the code :
import Handlebars from 'handlebars'
export default class Templating {
constructor() {
this._grabDom();
this._addListener();
this._getData();
this._putData();
}
/* PRIVATE METHODS */
_createBounds() {
['_getData', '_putData', '_prevent']
.forEach((fn) => this[fn] = this[fn].bind(this));
}
_putData() {
for (let i = 0; i < this._parsing.search.length; i++) {
let compiledTemplate = Handlebars.compile(this._dom.cardsTemplate);
let generated = compiledTemplate(this._parsing.search[i]);
this._dom.cardsContainer.innerHTML += generated
}
}
_getData() {
let req = new XMLHttpRequest();
req.open('GET', 'http://joibor.fr/api/search.json', false);
req.send(null);
if (req.status === 200) {
this._parsing = JSON.parse(req.responseText);
}
}
_prevent(pEvt) {
if (pEvt.keyCode === 13) {
pEvt.preventDefault();
this._value = pEvt.target.value;
}
}
/* END PRIVATE METHODS */
/* PUBLIC METHODS */
/* END PUBLIC METHODS */
/* EVENT HANDLER */
_addListener() {
this._dom.searchInput.addEventListener('keydown', this._prevent)
}
/* END EVENT HANDLER */
/* GRAB DOM */
_grabDom() {
this._dom = {};
this._dom.cardsTemplate = document.querySelector('#cards-template').innerHTML;
this._dom.cardsContainer = document.querySelector('.section-bottom__template');
this._dom.searchInput = document.querySelector('.js-search-input');
}
/* END GRAB DOM*/
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Search</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="section-top">
<form class="form">
<label class="form__label" for="">Lieux</label>
<input type="text" class="form__input js-search-input" placeholder="...">
</form>
</div>
<section class="section-bottom">
<h2 class="section-bottom__title">Les membres qui se trouvent à Reims</h2>
<div class="section-bottom__template"></div>
<script id="cards-template" type="text/x-handlebars-template">
<div class="cards">
<div class="cards__position">
<img class="cards__image" src="{{image}}" alt="profil 1">
<div class="cards-content">
<div class="about about--flex">
<p class="about__name">{{name}}</p>
<p class="about__city">{{city}}</p>
</div>
<div class="text">
<p class="text__content"><span class="text__content__cat">Disponible : </span> {{start}} <span class="text__content__cat">au</span> {{end}}</p>
</div>
<div class="place">
<p class="place__content"><span class="place__content__cat">Nombre max de voyageurs : </span> {{max}}</p>
</div>
</div>
</div>
</div>
</script>
</section>
<script src="js/script.js"></script>
</body>
</html>
Actually, the templating works but not the search I can't solved this problem.

Navigation between pages - html

I trying to navigate between 3 pages which contain the same header and footer but each page has different content.
I want to load different contents html on hash change.
The problem is that when I click on the same page again, the content.html loaded again.
How can I use the content without loading the html again and again, using java script/html/jquery?
Code example:
Navigationbar.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Navigation Bar</title>
<link rel="stylesheet" type="text/css" href="css/navigationbar.css">
</head>
<body>
<nav>
<img id="navigation-bar-logo" class="logo" src='images/flybryceLogo.png'>
<ul class="navigation-bar-ul">
<li class="navigation-bar-li"><a id="navigation-bar-contact-page-tab" href="#contact.html">CONTACT</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-about-us-page-tab" href="#aboutus.html">ABOUT US</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-home-page-tab" href="#home.html">HOME</a></li>
</ul>
</nav>
</body>
</html>
initial.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>One Page Test</title>
<link rel="stylesheet" type="text/css" href="css/homepage.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="main-container" class="main-container">
<div id="header" class="header">
</div>
<div id="content" class="content"></div>
<div id="footer" class="bot"></div>
</div>
<script>
document.onreadystatechange = function(){
if (document.readyState == 'complete') {
window.onhashchange=hash_change;
window.onload=hash_change;
if(window.location.hash==''){
//default hash
window.location.replace('#home.html');
}
//load the header
$("#header").load("fragments/navigationbar.html");
//load the footer
$("#footer").load("fragments/footer.html");
}
}
function hash_change()
{
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
$("#content").load("home.html");
} else if (newHashCode === "aboutus.html") {
$("#content").load("aboutus.html");
} else if (newHashCode === "contact.html"){
$("#content").load("contact.html");
}
}
</script>
</body>
</html>
A longer but suitable solution would be to build a content cache on your own.
For example asking to the server just once the html and then setting it to the $('#content') element. You can use this helper function.
var contentsCache = {};
var getAndCache = function(url, callback) {
var cachedContents = contentsCache[url];
if (!cachedContents) {
$.get(url, function(serverContents) {
cachedContents = serverContents;
contentsCache[url] = cachedContents;
callback(cachedContents);
});
} else {
callback(cachedContents);
}
};
And then replace the $('#content').load calls by calls to this new asynchronous way.
function hash_change()
{
var fillContentCb = function(s) {
$('#content').html(s);
};
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
getAndCache("home.html", fillContentCb);
} else if (newHashCode === "aboutus.html") {
getAndCache("aboutus.html", fillContentCb);
} else if (newHashCode === "contact.html"){
getAndCache("content.html", fillContentCb);
}
}
As suggested in some comments, consider using native HTML navigation instead. Another suggestion is to use a client-side JS framework which supports routing if this application is likely to grow.
Add an if condition that checks whether the current hash location matches with the one that's been clicked on, and if it does just return. You'd have to store it in a global JS variable, and set it every time you navigate.

PostMessage - Surface from Iframe to Parent

I have a website that contains an iframe. I want to track which button the user clicks inside the iframe and surface that information to the parent window. I looked into HTML5 PostMessage, but am unsure how I would tell the iframe where the parent is (line 3 in iframe.html). Do note that the parent and iframe have the same domain and protocol.
iframe.html
<script type="text/javascript">
var domain = window.location.protocol + '//' + window.location.hostname;
var parent = document.getElementById('parent').contentWindow; //what to do?
$('div').click( function() {
var message = $(this).text();
parent.postMessage(message,domain);
});
</script>
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
parent.html
<script type="text/javascript">
window.addEventListener('message', function(event) {
if(event.origin !== window.location.protocol + '//' + window.location.hostname;) {
return;
}
$('.message').html(event.data);
},false);
</script>
<div>
You have clicked on <span class="message"></span>
</div>
<iframe src="/iframe.html"></iframe>
I'm not sure how to do it in jQuery, however, here is a native way to communicate between parent and child frames in JavaScript.
The key code being:
var div = top.document.getElementById("topDiv");
Where top is the parent frame.
Parent.html
<!DOCTYPE html>
<html>
<head>
<title>Parent</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script>
function message() {
var child = document.getElementById("childFrame"),
div = child.contentWindow.document.getElementById("childDiv");
div.innerHTML = "TEXT";
}
function main() {
document.getElementById("messenger").addEventListener("click", function() {
message();
});
}
window.onload = main;
</script>
</head>
<body>
<iframe id="childFrame" src="child.html"></iframe>
<button id="messenger">Click Me</button>
<div id="topDiv"></div>
</body>
</html>
Child.html
<!DOCTYPE html>
<html>
<head>
<title>Child</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script>
function message() {
var div = top.document.getElementById("topDiv");
div.innerHTML = "TEXT";
}
function main() {
document.getElementById("messenger").addEventListener("click", function() {
message();
});
}
window.onload = main;
</script>
</head>
<body>
<div id="childDiv"></div>
<button id="messenger">Click Me</button>
</body>
</html>

Categories

Resources