This is what I have in my .pug file that I need the website to remember. If a user clicks the Large button then the website should remember that when the website is refreshed.
.scaling
scalingButton(onclick='body.style.fontSize = "1.0em"')='Normal'
scalingButton(onclick='body.style.fontSize = "1.2em"')='Medium'
scalingButton(onclick='body.style.fontSize = "1.5em"')='Large'
and here is what I have in the .css file for these buttons:
.scaling{
text-align: end;
position: fixed;
margin: 150px;
margin-right: 0%;
margin-bottom: 5%;
bottom: 0px;
right :20%;
}
scalingButton{
background-color: white;
padding: 5px 10px;
margin-top: 600px;
font-weight: bold;
border-radius: 3px;
border: 2px solid black;
filter: drop-shadow(2px 2px 2px black);
transition: 0.3s;
}
scalingButton:hover{
background-color: grey;
cursor: pointer;
}
You need to write a function that stores value in localStorage and when page is loaded (DOMContentLoaded ) you need to check localStorage, if localStorage has a font-size then you can apply it to the body.
script:
function changeFontSize(size) {
let fontSize = size + "em"
body.style.fontSize = fontSize;
localStorage.setItem('font-size', fontSize);
}
document.addEventListener("DOMContentLoaded", function(event) {
let fontSize = localStorage.getItem('font-size');
if(fontSize) {
body.style.fontSize = fontSize;
}
});
template
.scaling
scalingButton(onclick="changeFontSize('1.0em')")='Normal'
scalingButton(onclick="changeFontSize('1.2em')")='Medium'
scalingButton(onclick="changeFontSize('1.5em')")='Large'
Related
I have JS code on a webpage that loads questions in from mysql db and displays the text . What happens is that it cuts off words at the end of the line and continues the word on the next line at the start. So all text across the screen starts/ends at the same point.
This seems to be the code where it displays the text.
For example the text will look like at the end of a line 'cont' and then on next line at the start 'inue'.
How do i fix this?
var questions = <?=$questions;?>;
// Initialize variables
//------------------------------------------------------------------
var tags;
var tagsClass = '';
var liTagsid = [];
var correctAns = 0;
var isscorrect = 0;
var quizPage = 1;
var currentIndex = 0;
var currentQuestion = questions[currentIndex];
var prevousQuestion;
var previousIndex = 0;
var ulTag = document.getElementsByClassName('ulclass')[0];
var button = document.getElementById('submit');
var questionTitle = document.getElementById('question');
//save class name so it can be reused easily
//if I want to change it, I have to change it one place
var classHighlight = 'selected';
// Display Answers and hightlight selected item
//------------------------------------------------------------------
function showQuestions (){
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
if (currentIndex != 0) {
// create again submit button only for next pages
ulTag.innerHTML ='';
button.innerHTML = 'Submit';
button.className = 'submit';
button.id = 'submit';
if(quizPage<=questions.length){
//update the number of questions displayed
document.getElementById('quizNumber').innerHTML = quizPage;
}
}
//Display Results in the final page
if (currentIndex == (questions.length)) {
ulTag.innerHTML = '';
document.getElementById('question').innerHTML = '';
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
showResults();
return
}
questionTitle.innerHTML = "Question No:" + quizPage + " "+currentQuestion.question.category_name +"<br/>"+ currentQuestion.question.text;
if(currentQuestion.question.filename !== ''){
var br = document.createElement('br');
questionTitle .appendChild(br);
var img = document.createElement('img');
img.src = currentQuestion.question.filename;
img.className = 'imagecenter';
img.width = 750;
img.height = 350;
questionTitle .appendChild(img);
}
// create a for loop to generate the options and display them in the page
for (var i = 0; i < currentQuestion.options.length; i++) {
// creating options
var newAns = document.createElement('li');
newAns.id = 'ans'+ (i+1);
newAns.className = "notSelected listyle";
var textAns = document.createTextNode(currentQuestion.options[i].optiontext);
newAns.appendChild(textAns);
if(currentQuestion.options[i].file !== ''){
var br = document.createElement('br');
newAns .appendChild(br);
var img1 = document.createElement('img');
img1.src = currentQuestion.options[i].file;
img1.className = 'optionimg';
img1.width = 250;
img1.height = 250;
newAns .appendChild(img1);
newAns .appendChild(br);
}
var addNewAnsHere = document.getElementById('options');
addNewAnsHere.appendChild(newAns);
}
//.click() will return the result of $('.notSelected')
var $liTags = $('.notSelected').click(function(list) {
list.preventDefault();
//run removeClass on every element
//if the elements are not static, you might want to rerun $('.notSelected')
//instead of the saved $litTags
$liTags.removeClass(classHighlight);
//add the class to the currently clicked element (this)
$(this).addClass(classHighlight);
//get id name of clicked answer
for (var i = 0; i < currentQuestion.options.length ; i++) {
// console.log(liTagsid[i]);
if($liTags[i].className == "notSelected listyle selected"){
//store information to check answer
tags = $liTags[i].id;
// tagsClass = $LiTags.className;
tagsClassName = $liTags[i];
}
}
});
//check answer once it has been submitted
button.onclick = function (){
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
setTimeout(function() { checkAnswer(); }, 100);
};
}
//self calling function
showQuestions();
The website is on my local now but i can upload a screenimage if need be and the whole code of the webpage. Or is the issue in html?
edit: here is html/css code
<style>
/*========================================================
Quiz Section
========================================================*/
/*styling quiz area*/
.main {
background-color: white;
margin: 0 auto;
margin-top: 30px;
padding: 30px;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
/*white-space: nowrap;*/
}
/*Editing the number of questions*/
.spanclass {
font-size: x-large;
}
#pages{
border: 3px solid;
display: inline-flex;
border-radius: 0.5em;
float: right;
}
#question{
word-break: break-all;
}
/*format text*/
p {
text-align: left;
font-size: x-large;
padding: 10px 10px 0;
}
.optionimg{
border: 2px solid black;
border-radius: 1.5em;
}
/*Form area width*/
/*formatting answers*/
.listyle {
list-style-type: none;
text-align: left;
background-color: transparent;
margin: 10px 5px;
padding: 5px 10px;
border: 1px solid lightgray;
border-radius: 0.5em;
font-weight: normal;
font-size: x-large;
display: inline-grid;
width: 48%;
height: 300px;
overflow: auto;
}
.listyle:hover {
background: #ECEEF0;
cursor: pointer;
}
/*Change effect of question when the questions is selected*/
.selected, .selected:hover {
background: #FFDEAD;
}
/*change correct answer background*/
.correct, .correct:hover {
background: #9ACD32;
color: white;
}
/*change wrong answer background*/
.wrong, .wrong:hover {
background: #db3c3c;
color: white;
}
/*========================================================
Submit Button
========================================================*/
.main button {
text-transform: uppercase;
width: 20%;
border: none;
padding: 15px;
color: #FFFFFF;
}
.submit:hover, .submit:active, .submit:focus {
background: #43A047;
}
.submit {
background: #4CAF50;
min-width: 120px;
}
/*next question button*/
.next {
background: #fa994a;
min-width: 120px;
}
.next:hover, .next:active, .next:focus {
background: #e38a42;
}
.restart {
background-color:
}
/*========================================================
Results
========================================================*/
.circle{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: #bdc3c7;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
overflow: hidden;
}
.fill{
position: absolute;
bottom: 0;
width: 100%;
height: 80%;
background: #31a2ac;
}
.score {
position: absolute;
width: 100%;
top: 1.7em;
text-align: center;
font-family: Arial, sans-serif;
color: #fff;
font-size: 40pt;
line-height: 0;
font-weight: normal;
}
.circle p {
margin: 400px;
}
/*========================================================
Confeeti Effect
========================================================*/
canvas{
position:absolute;
left:0;
top:11em;
z-index:0;
border:0px solid #000;
}
.imagecenter{
display: block;
margin: 0 auto;
}
.buttonload {
background-color: #04AA6D; /* Green background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 12px 24px; /* Some padding */
font-size: 16px; /* Set a font-size */
}
/* Add a right margin to each icon */
.fa {
margin-left: -12px;
margin-right: 8px;
}
#media only screen and (max-width: 900px){
.listyle {
width: 100% !important;
height: auto !important;
}
.imagecenter {
width: 100% !important;
}
.listyle img{
width: inherit !important;
height: unset !important;
}
.ulclass
{
padding:0px !important;
}
}
</style>
<!-- Main page -->
<div class="main">
<!-- Number of Question -->
<div class="wrapper" id="pages">
<span class="spanclass" id="quizNumber">1</span><span class="spanclass">/<?=$count?></span>
</div>
<!-- Quiz Question -->
<div class="quiz-questions" id="display-area">
<p id="question"></p>
<ul class="ulclass" id="options">
</ul>
<div id="quiz-results" class="text-center">
<button type="button" name="button" class="submit" id="submit">Submit</button>
</div>
</div>
</div>
<canvas id="canvas"></canvas>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
I'm guessing that #question{ word-break: break-all; } is probably the culprit then? –
CB..yes that fixed it:)
Id like to make a component in react that allows me to have a textarea with tags that can be inserted when clicked from a dropdown. Id also like this textarea to be able to mix text aswell. I have currently been trying to use tagify with react but I cant seem to figure out a way to the tagify's function that adds the tag to be accessed by the onClick that is connected to the dropdown.
Any ideas?
I believe you can get your answer in this URL of other question asked on StackOverflow https://stackoverflow.com/a/38119725/15405352
var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');
// yeah, browser sniffing sucks, but there are browser-specific quirks to handle that are not a matter of feature detection
var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);
function applyHighlights(text) {
text = text
.replace(/\n$/g, '\n\n')
.replace(/[A-Z].*?\b/g, '<mark>$&</mark>');
if (isIE) {
// IE wraps whitespace differently in a div vs textarea, this fixes it
text = text.replace(/ /g, ' <wbr>');
}
return text;
}
function handleInput() {
var text = $textarea.val();
var highlightedText = applyHighlights(text);
$highlights.html(highlightedText);
}
function handleScroll() {
var scrollTop = $textarea.scrollTop();
$backdrop.scrollTop(scrollTop);
var scrollLeft = $textarea.scrollLeft();
$backdrop.scrollLeft(scrollLeft);
}
function fixIOS() {
// iOS adds 3px of (unremovable) padding to the left and right of a textarea, so adjust highlights div to match
$highlights.css({
'padding-left': '+=3px',
'padding-right': '+=3px'
});
}
function bindEvents() {
$textarea.on({
'input': handleInput,
'scroll': handleScroll
});
$toggle.on('click', function() {
$container.toggleClass('perspective');
});
}
if (isIOS) {
fixIOS();
}
bindEvents();
handleInput();
#import url(https://fonts.googleapis.com/css?family=Open+Sans);
*, *::before, *::after {
box-sizing: border-box;
}
body {
margin: 30px;
background-color: #f0f0f0;
}
.container, .backdrop, textarea {
width: 460px;
height: 180px;
}
.highlights, textarea {
padding: 10px;
font: 20px/28px 'Open Sans', sans-serif;
letter-spacing: 1px;
}
.container {
display: block;
margin: 0 auto;
transform: translateZ(0);
-webkit-text-size-adjust: none;
}
.backdrop {
position: absolute;
z-index: 1;
border: 2px solid #685972;
background-color: #fff;
overflow: auto;
pointer-events: none;
transition: transform 1s;
}
.highlights {
white-space: pre-wrap;
word-wrap: break-word;
color: transparent;
}
textarea {
display: block;
position: absolute;
z-index: 2;
margin: 0;
border: 2px solid #74637f;
border-radius: 0;
color: #444;
background-color: transparent;
overflow: auto;
resize: none;
transition: transform 1s;
}
mark {
border-radius: 3px;
color: transparent;
background-color: #b1d5e5;
}
button {
display: block;
width: 300px;
margin: 30px auto 0;
padding: 10px;
border: none;
border-radius: 6px;
color: #fff;
background-color: #74637f;
font: 18px 'Opens Sans', sans-serif;
letter-spacing: 1px;
appearance: none;
cursor: pointer;
}
.perspective .backdrop {
transform:
perspective(1500px)
translateX(-125px)
rotateY(45deg)
scale(.9);
}
.perspective textarea {
transform:
perspective(1500px)
translateX(155px)
rotateY(45deg)
scale(1.1);
}
textarea:focus, button:focus {
outline: none;
box-shadow: 0 0 0 2px #c6aada;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="backdrop">
<div class="highlights"></div>
</div>
<textarea>This demo shows how to highlight bits of text within a textarea. Alright, that's a lie. You can't actually render markup inside a textarea. However, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there. JavaScript takes care of syncing the content and scroll position from the textarea to the div, so everything lines up nicely. Hit the toggle button to peek behind the curtain. And feel free to edit this text. All capitalized words will be highlighted.</textarea>
</div>
<button>Toggle Perspective</button>
Reference- https://codepen.io/lonekorean/pen/gaLEMR for example
I am wondering how to change the border of lock:before to solid transparent when the correct password is entered.
My JavaScript is like this, I need a lock before value to change to solid transparent when the IF is triggered
function lock(){
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
alert("Lock opened");
} else {
alert("Wrong password");
}
}
My CSS is like this, lock before needs to be changed to solid transparent by a javascript function.
body {
position: absolute;
color: #00ff80;
background: green;
top: 100px;
left: 200px;
}
#lock {
font-size: 8px;
position: relative;
width: 18em;
height: 13em;
border-radius: 2em;
top: 10em;
box-sizing: border-box;
border: 3.5em solid red;
border-right-width: 7.5em;
border-left-width: 7.5em;
margin: 0 0 6rem 0;
}
#lock:before {
content: "";
box-sizing: border-box;
position: absolute;
border: 2.5em solid red;
width: 14em;
height: 12em;
left: 50%;
margin-left: -7em;
top: -12em;
border-top-left-radius: 7em;
border-top-right-radius: 7em;
}
#lock:after {
content: "";
box-sizing: border-box;
position: absolute;
border: 1em solid red;
width: 5em;
height: 8em;
border-radius: 2.5em;
left: 50%;
top: -1em;
margin-left: -2.5em;
}
#button {
background: transparent;
}
My HTML is like this, all it does is make a button and some text.
<!DOCTYPE html>
<html>
<head>
<title>The lock</title>
</head>
<body>
<h1>Unlock the lock</h1>
<button id=button onclick="lock()"><div id=lock></div></button>
</body>
</html>
Try something like this..
var str = '1em solid transparent';
document.styleSheets[0].addRule('#lock:before','border: "'+str+'";');
the style of a pseudo-element can be changed by using a new class name. For example, add the class name unlocked to the #lock element once the entered password is valid.
You can add the following style for the new class:
#lock.unlocked::before {
border: 1em solid transparent;
/* Your style for unlocked goes here */
}
And your script with the new instruction which add the class .unlocked.
function lock() {
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
alert("Lock opened");
document.getElementById("lock").classList.add("unlocked"); /* NEW */
} else {
alert("Wrong password");
}
}
Add and remove a class to and from the button. Pseudo elements can't be targeting directly from JavaScript so you have to use CSS to change the styling.
// Select the button
const button = document.querySelector('button');
function lock(){
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
// Add the class.
button.classList.add('unlocked');
// If it already has the class..
} else if (button.classList.contains('unlocked')) {
//.. then remove it.
button.classList.remove('unlocked');
}
}
And in your CSS add the class with the styling you need.
#lock.unlocked::before {
border: 2.5em solid transparent;
}
I have just found a set of codes that fits my need right now for my blog.
Here I'll attach the code and a glimpse of what it looks like. Although It's still very simple.
What I want to ask is if it's possible to tweak these code possible using JS localstorage, so that it will keep all the saved text even after the user refresh the page, or even better if it stays there even after a user closed the window and reopened it later?
Here's what it looks like right now
and here is the code:
$(document).ready(function(){
var noteCount = 0;
var activeNote = null;
$('.color-box').click(function(){
var color = $(this).css('background-color');
$('notepad').css('background-color', color);
$('#title-field').css('background-color', color);
$('#body-field').css('background-color', color);
})
$('#btn-save').click(function(){
var title = $('#title-field').val();
var body = $('#body-field').val();
if (title === '' && body === '') {
alert ('Please add a title or body to your note.');
return;
}
var created = new Date();
var color = $('notepad').css('background-color');
var id = noteCount + 1;
if (activeNote) {
$('#' + activeNote)[0].children[0].innerHTML = title;
$('#' + activeNote)[0].children[1].innerHTML = created.toLocaleString("en-US");
$('#' + activeNote)[0].children[2].innerHTML = body;
$('#' + activeNote)[0].style.backgroundColor = color;
activeNote = null;
$('#edit-mode').removeClass('display').addClass('no-display');
} else {
var created = new Date();
$('#listed').append('<div id="note' + id + '" style="background-color: ' + color + '"><div class="list-title">' + title + '</div> <div class="list-date">' + created.toLocaleString("en-US") + '</div> <div class="list-text">' + body + '</div> </div>');
noteCount++;
};
$('#title-field').val('');
$('#body-field').val('');
$('notepad').css('background-color', 'white');
$('#title-field').css('background-color', 'white');
$('#body-field').css('background-color', 'white');
});
$('#btn-delete').click(function(){
if (activeNote) {
$('#' + activeNote)[0].remove();
activeNote = null;
$('#edit-mode').removeClass('display').addClass('no-display');
}
$('#title-field').val('');
$('#body-field').val('');
$('notepad').css('background-color', 'white');
$('#title-field').css('background-color', 'white');
$('#body-field').css('background-color', 'white');
});
$('#listed').click(function(e){
var id = e.target.parentElement.id;
var color = e.target.parentElement.style.backgroundColor;
activeNote = id;
$('#edit-mode').removeClass('no-display').addClass('display');
var titleSel = $('#' + id)[0].children[0].innerHTML;
var bodySel = $('#' + id)[0].children[2].innerHTML;
$('#title-field').val(titleSel);
$('#body-field').val(bodySel);
$('notepad').css('background-color', color);
$('#title-field').css('background-color', color);
$('#body-field').css('background-color', color);
})
})
header {
text-align: left;
font-weight: 800;
font-size: 28px;
border-bottom: solid 3px #DEDEDE;
display: flex;
justify-content: space-between;
}
footer {
display: flex;
flex-flow: row-reverse;
padding: 5px 20px;
}
.headers {
margin-top: 20px;
margin-bottom: -10px;
font-size: 20px;
}
#list-head {
margin-left: 2.5%;
width: 30.5%;
display: inline-block;
text-align: center;
}
#note-head {
width: 60%;
margin-left: 5%;
display: inline-block;
text-align: center;
}
noteList {
margin-top: 20px;
display: inline-block;
margin-left: 2.5%;
width: 30.5%;
height: 400px;
overflow: scroll;
border: solid 3px #929292;
border-radius: 5px;
background-color: #DEDEDE;
}
.within-list {
cursor: pointer;
}
.list-title {
font-weight: 600;
font-size: 20px;
padding: 5px 5px 0 5px;
}
.list-date {
font-weight: 200;
font-style: italic;
font-size: 12px;
padding: 0 5px 0 5px;
}
.list-text {
padding: 0 5px 5px 5px;
border-bottom: solid 1px black;
}
notePad {
display: inline-block;
border: solid 3px black;
border-radius: 10px;
height: 400px;
overflow: scroll;
width: 60%;
margin-left: 5%;
margin-top: 0;
}
#note-title {
font-size: 24px;
padding: 0 0 5px 5px;
border-bottom: solid 2px #DEDEDE;
}
#note-body {
padding: 5px;
}
#body-field, #title-field {
width: 100%;
border: none;
outline: none;
resize: none;
}
#title-field {
font-size: 18px;
font-weight: 600;
}
#body-field {
font-size: 14px;
font-weight: 500;
height: 400px;
}
#color-select {
display: flex;
flex-flow: row-reverse nowrap;
padding: 5px 10px 0 0;
}
.color-box {
border: solid 2px #929292;
height: 10px;
width: 10px;
margin-left: 5px;
}
.display {
display: visible;
}
.no-display {
display: none;
}
button {
margin: 5px;
border: solid 3px grey;
border-radius: 10%;
font-size: 22px;
font-weight: 800;
text-transform: uppercase;
color: #DEDEDE;
}
button:hover, .color-box:hover {
cursor: pointer;
}
#listed:nth-child(odd):hover {
cursor: pointer;
}
#btn-save {
background-color: #2F5032;
}
#btn-delete {
background-color: #E41A36;
}
.white {
background-color: white;
}
.orange {
background-color: #FFD37F;
}
.banana {
background-color: #FFFA81;
}
.honeydew {
background-color: #D5FA80;
}
.flora {
background-color: #78F87F;
}
.aqua {
background-color: #79FBD6;
}
.ice {
background-color: #79FDFE;
}
.sky {
background-color: #7AD6FD;
}
.orchid {
background-color: #7B84FC;
}
.lavendar {
background-color: #D687FC;
}
.pink {
background-color: #FF89FD;
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title></title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
The Note Machine
<div id='color-select'>
<div class='color-box white'></div>
<div class='color-box orange'></div>
<div class='color-box banana'></div>
<div class='color-box honeydew'></div>
<div class='color-box flora'></div>
<div class='color-box aqua'></div>
<div class='color-box ice'></div>
<div class='color-box sky'></div>
<div class='color-box orchid'></div>
<div class='color-box lavendar'></div>
<div class='color-box pink'></div>
</div>
</header>
<main>
<div class="headers">
<div id="list-head">
<b>Your Notes</b> <i>(click to edit/delete)</i>
</div>
<div id="note-head">
<b>Your Notepad</b>
<span id="edit-mode" class="no-display">
<i> (edit mode) </i>
</span>
</div>
</div>
<noteList>
<div id='listed'>
</div>
</noteList>
<notepad>
<div id="note-title">
<input id="title-field" type="text" placeholder="title your note">
</div>
<div id="note-body">
<textarea id="body-field"></textarea>
</div>
</notepad>
</main>
<footer>
<button id="btn-save">Save</button>
<button id="btn-delete">Delete / Clear </button>
</footer>
</body>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
<script type='text/javascript' src='app.js'></script>
</html>
I tried searching in the net for other notepads, but they aren't working on my blog, and here's the one that is finally working. I would really appreciate any kind of suggestions and assistance. T
If all you want to do is save to LocalStorage when save is clicked, then it would be as simple as saving the title and body variables to LocalStorage in the $('#btn-save').click() handler.
Assuming that (as #Nawed Khan guessed) you want to have the note saved without the user having to click save, then you'll want to make three changes:
In the main body of your $(document).ready() function, check for existing LocalStorage values, and if they exist, then set them on your $('#title-field') and $('#body-field') elements.
Add two new change handlers to your $('#title-field') and $('#body-field') elements. When these change handlers fire, get the title and body values from the elements and save them to LocalStorage.
In the $('#btn-save').click() and $('#btn-delete').click() handlers, reset the LocalStorage values of the active note.
You should find these links useful:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
https://api.jquery.com/change/
P.S. The information stored in LocalStorage can be lost if the user chooses to clear their browser data. If preservation of the data is vital, then implementing a solution using AJAX to connect to a database as #The Rahul Jha suggested would guarantee preservation of the data.
Yes , You can save the data in localStorage and fetch the data on page load. To set the localStorage item add below function in your script which is setting the item on keyup of textarea in localstorage.
$(document).on("keyup","#body-field",function(){
var text = $("#body-field").val();
localStorage.setItem("savedData", text);
});
Add below method to fetch the data from local storage
function loadDataFromLocalStorage(){
if (localStorage.getItem("savedData") !== null) {
$("#body-field").val(localStorage.getItem("savedData"))
}
}
And at last call the above method in $(document).ready() or page load to set the data back in text area after page load.
Put this inside the $(document).ready block:
$(“#title-field”).val(window.localStorage.getItem(“title”) || “”);
$(“#body-field”).val(window.localStorage.getItem(“body”) || “”);
$(“#title-field, #body-field”).change(function() {
var title = $(“#title-field”).val();
var body = $(“#body-field”).val();
window.localStorage.setItem(“title”, title);
window.localStorage.setItem(“body”, body)
})
The 2 first lines will load the text from the localStorage and sets the data on the corresponding inputs
The rest of the code is the part where the data is being saved to localStorage every time the value of #title-field OR #body-field changes.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This code is an excerpt from a larger project, but I have tried to pull out the relevant material and provide that only.
I have a project, and the part that I need help with is this:
Product codes are generated by users via a series of drop-downs and radio buttons. The one part that will always stay the same is that there is a
(x11)
at the end of each line with a product number, where 11 represents the quantity of the product code, and will also change.
A demo of the relevant code is available at This Fiddle.
My problem is this: the deleteItem() function works when the code is displayed as
ca-fefefsefef (x45)
but not when I tried to change the format to display the quantity as
ca-fjeoisfne Qty. 78
(The difference being in the way the quantity is displayed, not the code itself)
All of the product codes are examples, are not real, and the actual codes will vary in length and content. The quantity of each product code will change as well.
I suppose what I am asking for is a new regex to replace the old one in the deleteitem() function, but this regex needs to work with
Qty. 23
where 23 is the quantity, and will change from code to code.
Basically, the selection of code that I have provided at the fiddle is designed to display each product code and its corresponding quantity in a drop down. The codes are stored in an array, as well as the quantities(in a separate array). The purpose of the deleteitem() function is when the delete button is clicked next to a product code and quantity, it not only deletes the product code and quantity from the drop-down, but it also deletes the corresponding items in the product_codes and quantities arrays. (with the help of the removetextfromarray() function)
Make sure to watch the web console, it will display the arrays before and after the items are deleted. You'll note that when the quantity is displayed as (x99), it works, but if you change it to Qty. 99, it removes the items from the dropdown, but does not remove the corresponding items from their arrays.
So what I need is a new regex to replace the old one (or possibly a new/updated deleteitem() function that will work with the quantity display format as
Qty. 3
instead of
(x3)
and will delete both the items both from the drop down, and delete the two items from their corresponding arrays.
Please keep in mind the following: The product codes in the array, and the quantities in their own array will change, the ones I have provided are examples. There may be more than three, and they will change in length. I am also unable to use Jquery.
If you can spare the time, I would love any help you can give. I've spent literally hours trying to build new regexes that will work, trying to uncode the existing one (I didn't write it) and such. A working fiddle would be absolutely GREAT. Thanks so much for any help.
If I'm not being clear, please comment and I'll be happy to answer any questions about it or make updates. Thanks again!
How about this: /\w*Qty\. \d+$/
(see example here https://jsfiddle.net/xes3eLxp/1/)
That means, match:
Zero or more white space characters (\w*),
Qty. (Qty\.),
A single space (),
One or more digits (\d+),
The end of the line ($).
Consider the sample string: "ckj-fjeieofj Qty. 56"
The above regex would match Qty. 56
product_codes = ['cr-rttrnhuj3', 'ckj-fjeieofj', 'jjff-cr-sd'];
quantities = ['2', '56', '98'];
myfunction = function () {
document.getElementById('cart_body').innerHTML = '';
cart_text = '';
emp = '<div class="close_button" onclick="deleteItem(this)">x</div>';
open_span = '<span class="close_span">';
close_span = '</span>';
elf = '<br class="none"/>';
for (i = 0; i < product_codes.length; i++) {
cart_text += "<div>" + open_span + product_codes[i] + " Qty. " + quantities[i] + close_span + emp + elf + "</div>";
}
document.getElementById('cart_body').innerHTML = cart_text;
}
function removeTextFromArray(array, text){
for (var i=array.length-1; i>=0; i--) {
if (array[i] === text) {
array.splice(i, 1);
quantities.splice(i, 1);
return array;
}
}
}
myfunction();
hider2 = function () {
cart_bod = document.getElementById('cart_body');
cart_bod.classList.toggle('closed');
}
//below function is the important one
deleteItem = function (item) {
//dot instead of hashtag
item.parentElement.remove();
console.log('set');
var textInNode = item.parentElement.getElementsByClassName("close_span")[0].innerHTML;
textInNode = textInNode.replace(/\w*Qty\. \d+$/g, "").trim();
//new regex is /*\Qty[^)]*\ */g
//old is / *\([^)]*\) */g
codes = removeTextFromArray(product_codes, textInNode);
console.log(product_codes)
console.log(quantities);
}
body {
font: 12px tahoma;
}
.centered {
border: 2px solid transparent;
margin: 0 auto;
width: 90%;
margin-bottom: 10px;
}
#debug-box {
}
#configurator-container {
}
#submit-box {
width: 400px;
height: 50px;
margin-bottom: 5px;
}
#unit-container {
border: 2px solid transparent;
width: 50%;
/*change this width to test whether it'll fit in the SEI website'*/
}
#quantity {
width: 40px;
}
.select-label {
}
dt {
float: left;
width: 45%;
text-align: right;
cursor: default;
}
br {
margin-bottom: 30px;
}
.none {
margin-bottom: 0px;
}
.s_container {
margin-top: 20px;
}
.sm_it {
font-style: italic;
}
i {
padding-left: 20px;
font-size: 10px;
}
input[type='email'] {
width: 235px;
}
.second_line_italics {
padding-left: 40px;
}
#configurator-container {
background-image: url("data:image/gif;base64,R0lGODlhBgAGAKIAANbXy+Hi29rc08THu9HWy8zQwwAAAAAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS4wLWMwNjAgNjEuMTM0Nzc3LCAyMDEwLzAyLzEyLTE3OjMyOjAwICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOkYzM0I5RTQ3Q0UwRUUwMTFCMzMzRkRGNDFGODlGRDVEIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkY2QjNGNjE4ODQ5ODExRTA4MUU4OTkzQzdFOTQ5MDU5IiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkY2QjNGNjE3ODQ5ODExRTA4MUU4OTkzQzdFOTQ5MDU5IiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzQgV2luZG93cyI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjcyMDlGMEYwQjg2QUUwMTFCOTg2OTk5N0I0QjM1NDEyIiBzdFJlZjpkb2N1bWVudElEPSIxNzA3NiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PgH//v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh5N/e3dzb2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vLu6ubi3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZmJeWlZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJCAcGBQQDAgEAACH5BAAAAAAALAAAAAAGAAYAAAMQSBpcLnBIQFlQBApXKJBDAgA7");
}
select {
width: 235px;
}
input[type='number'] {
width: 235px;
}
.twin_btns {
display: inline;
cursor: pointer;
}
.twin_divs {
margin: 0 auto;
margin-top: 10px;
z-index: 300;
position relative;
text-align: center;
}
#second_line_ex-length {
width: 215px;
margin-left: 20px;
}
#b-length-1 {
width: 145px;
}
#b-length-2 {
width: 145px;
}
.hidden {
color: grey;
pointer-events: none;
pointer: default;
border-color: grey;
}
.contact-i-header {
font-weight: bold;
font-size: 18px;
}
input[type='text'] {
width: 235;
}
#request-quote-container {
height: 60px;
width: 90%;
margin:0 auto;
border-bottom: 1px solid #ADAEA9;
font-family: Tahoma;
background-color: #DADCD3;
}
h2 {
opacity: .8;
width: 284.917px;
text-align: right;
}
.side-by-side {
display: inline-block;
}
h5 {
margin-left: 40px;
}
#item {
margin-top: 5px;
}
#triangle-up {
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 10px solid black;
opacity: 0.6;
}
.slider {
overflow-y: hidden;
transition-property: all;
transition-duration: 5s;
transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
}
.slider.closed {
max-height: 0;
}
.slider2 {
overflow-y: hidden;
transition-property: all;
transition-duration:.5s;
transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
max-height: 200px;
}
.slider2.closed {
max-height: 0;
}
#submit_info {
text-align: center;
margin: 0 auto;
}
.bottom_btns {
}
#sent_box {
height: 20px;
text-align: center;
}
#write_box {
height: 20px;
text-align: center;
}
#send_box {
height: 20px;
text-align: center;
}
.cart_parts {
border: 1px solid black;
box-sizing: border-box;
width: 60%;
margin: 0 auto;
}
#cart_top {
height: 40px;
font-family: Tahoma;
background-color: #DADCD3;
margin: 0 auto;
box-shadow:
}
#cart_body {
text-align: center;
}
.close_button {
border: 1px solid black;
width: 12px;
height: 12px;
border-radius: 90px;
font-size: 12px;
text-align: center;
line-height: 11px;
background-color: lightGrey;
display: inline-block;
margin-left: 20px;
}
.close_span {
display: inline-block;
}
.close_button:hover {
color: red;
border: 2px solid red;
font-weight: bold;
}
#script_no {
color: red;
text-align: center;
font-size: 16px;
}
#not_supported {
text-align: center;
color: red;
}
#ter {
margin-bottom: 30px;
background-color: red;
}
#submit-box {
margin: 45px auto;
}
#tbr {
margin-bottom:10px;
}
<div id='cart_top' class='cart_parts'> <dt class='list-item' style='margin-top: 10px;'>
View your Quote
</dt>
<dd class='list-item'>
<div id='triangle-up' class='side-by-side' style='float: right; margin-right: 20px; cursor: pointer; margin-top: 15px;' onClick='hider2()'></div>
</dd>
</div>
<div id='cart_body' class='cart_parts slider2 closed'></div>