Every time I delete a cookie, the content I wrote disappears - javascript

With full force I am creating a notepad that can permanently save the written contents.
Below is the actual code.
・ insertHTML & CSS
window.addEventListener('load', l => {
document.querySelector("body")
.insertAdjacentHTML('beforebegin', `
<!-- MEMO FORM -->
<div class="toolbar__centerfont" style=margin-top:50px;>
<font color="#4689FF" size="4.5";>Notepad No.1</font>
</div>
<textarea id="sample-text_1" class="My_textarea" rows="4" cols="24"></textarea>
<style>
#sample-text_1{
border:solid 1px blue;
outline:0;
min-height:80px;
min-width:235.85px;
font-size:9pt;}
</style>
<input type="button" id="sample-save_1" value="SAVE" onclick="savetext_1()" />
<style>
#sample-save_1{
display:block;
margin:0;
margin-top:-5.7px;
margin-left:0.5px;
width:45px;
height:18px;
font-size:8.5px;
background:#DDDDDD;
border-width:1px;
border-color:#23003a;
border-style:solid;
cursor:pointer;}
</style>
<input type="button" id="sample-delete_1" value="delete" onclick="deletetext_1()"/>
<style>
#sample-delete_1{
display:block;
margin:0;
margin-top:-18px;
margin-left:50px;
width:45px;
height:18.2px;
font-size:8.5px;
background:#DDDDDD;
border-width:1px;
border-color:#23003a;
border-style:solid;
cursor:pointer;}
</style>
<div class="toolbar__centerfont" style=margin-top:20px;>
<font color="#4689FF" size="4.5";>Notepad No.4</font>
</div>
<textarea id="sample-text_4" class="My_textarea" rows="4" cols="24"></textarea>
<style>
#sample-text_4{
border:solid 1px blue;
outline:0;
min-height:80px;
min-width:235.85px;
font-size:9pt;}
</style>
<input type="button" id="sample-save_4" value="SAVE" onclick="savetext_4()" />
<style>
#sample-save_4{
display:block;
margin:0;
margin-top:-5.7px;
margin-left:0.5px;
width:45px;
height:18px;
font-size:8.5px;
background:#DDDDDD;
border-width:1px;
border-color:#23003a;
border-style:solid;
cursor:pointer;}
</style>
<input type="button" id="sample-delete_4" value="delete" onclick="deletetext_4()" />
<style>
#sample-delete_4{
display:block;
margin:0;
margin-top:-18px;
margin-left:50px;
width:45px;
height:18.2px;
font-size:8.5px;
background:#DDDDDD;
border-width:1px;
border-color:#23003a;
border-style:solid;
cursor:pointer;}
</style>
<!-- End MEMO FORM -->
`);
});
・ JavaScript Processing content
window.addEventListener('load', ll => {
if (localStorage.getItem('memo_1') === null) {
return false;
}
var text_1 = localStorage.getItem('memo_1');
document.getElementById("sample-text_1").value = text_1;
});
// Text area_1 Save button processing
function savetext_1() {
var save_text_1 = document.getElementById("sample-text_1").value;
if (!save_text_1) {
return false;
}
localStorage.setItem('memo_1', save_text_1);
function set_color() {
document.getElementById("sample-text_1")
.style.backgroundColor = '#e1fddb';
}
let set_C = setInterval(set_color, 100);
function stop_color() {
clearInterval(set_C);
document.getElementById("sample-text_1")
.style.backgroundColor = '#fff';
}
setTimeout(stop_color, 2500);
}
// Text area_1 Delete button processing
function deletetext_1() {
if (localStorage.getItem('memo_1') === null) {
return false;
}
localStorage.removeItem('memo_1');
document.getElementById("sample-text_1").value = '';
}
I was quite happy with the moment it was completed, but there is one problem.
Every time you delete a cookie, the content you wrote down will be lost.
I want to keep what I wrote even if I delete the cookie.
Is that possible?
There is no basis, but here's what I've tried:
window.addEventListener('load', ll => {
if(localStorage.getItem('memo_4') === null){
return false;
}
var text_4 = localStorage.getItem('memo_4');
document.getElementById("sample-text_4").value = text_4;
document.cookie = "memo_4=save_text_4; expires=Sun, 01 Jan 2045 00:00:00 GMT";
let cookies_4_get = document.cookie;
cookies_4_get;
let cookies_4_set = encodeURIComponent(save_text_4);
document.cookie = 'memo_4' + cookies_4_set;
});
// Text area_4 Save button processing
function savetext_4(){
var save_text_4 = document.getElementById("sample-text_4").value;
if(!save_text_4){
return false;
}
localStorage.setItem('memo_4', save_text_4);
let cookies_4_get = document.cookie;
cookies_4_get;
document.cookie = "memo_4=save_text_4; expires=Sun, 01 Jan 2045 00:00:00 GMT";
//document.getElementById("sample-text_4").value = save_text_4;
function set_color(){
document.getElementById("sample-text_4")
.style.backgroundColor = '#e1fddb';
}
let set_C = setInterval(set_color, 100);
function stop_color(){
clearInterval(set_C);
document.getElementById("sample-text_4")
.style.backgroundColor = '#fff';
}
setTimeout(stop_color, 2500);
}
// Text area_4 Delete button processing
function deletetext_4(){
if(localStorage.getItem('memo_4') === null){
return false;
}
localStorage.removeItem('memo_4');
document.getElementById("sample-text_4").value ='';
document.cookie = "memo_4=; max-age=0";
}
Is it the limit of what can be done with the front end in the first place?
If so, how can I save my local storage permanently?
Operating environment
WINDOWS10, GoogleChrome 64bit
https://chrome.google.com/webstore/detail/user-javascript-and-css/nbhcbdghjpllgmfilhnhkllmkecfmpld

Related

How do I write a javascript with a for loop that repeats a word?

I'm self taught in javascript but I have been struggling to do this, I want to create a js where it has two functions, one works just for the "for loop". And the second one goes for the buttom which only will ask the user two questions with two prompts, one word, and how many times does the user would like to repeat it.
for example, if the user writes "Hello" in the first prompt and then writes "3" in the second prompt question, the outpur needs to be "HelloHelloHello"
I would really appreciate your help,
this is my html
<!DOCTYPE html>
<html>
<head>
<script src="practice1.js"></script>
<title>Repetition</title>
</head>
<body>
<h1> repetition of words </h1>
<p id="resultLoop"> ----- </p>
<button onclick="askUser()">Do the repetitions</button>
</body>
</html>
If you need to use a for loop, then there are a few ways to do this. One way would be to create an array and push the string they input an n number of times. Then join them together.
Example:
let result = [];
const n = 3;
const stringToRepeat = "hello";
for (let i = 0; i < n; i++) {
result.push(stringToRepeat);
}
result = result.join("");
console.log(result);
Output:
hellohellohello
Another way would be to simply concatenate the strings within each iteration of your for loop. Example:
let result = "";
const n = 3;
const stringToRepeat = "hello";
for (let i = 0; i < n; i++) {
result += stringToRepeat;
}
console.log(result);
Output:
hellohellohello
Although String.prototype.concat() also concatenates strings, they recommend using assignment operators for performance reasons.
If you didn't need to use a for loop, then String.prototype.repeat() does exactly what you want. Although, it is still not compatible with Internet Explorer.
Here's an example of what I mean:
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC, allGood; // for reuse on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = (node, className)=>{
return node.classList.contains(className);
}
aC = function(){
const a = [...arguments];
a.shift().classList.add(...a);
return aC;
}
rC = function(){
const a = [...arguments];
a.shift().classList.remove(...a);
return rC;
}
tC = function(){
const a = [...arguments];
a.shift().classList.toggle(...a);
return tC;
}
allGood = nodeArray=>{
for(let n of nodeArray){
if(!hC(n, 'good')){
return false;
}
}
return true;
}
// small library above - magic below can be put on another page using a load Event (except // end load line)
const rep_text = I('rep_text'), rep_x = I('rep_x'), rep_it = I('rep_it'), out = I('output'), goods = [rep_text, rep_x];
rep_text.oninput = function(){
let f = this.value.trim() === '' ? rC : aC; // remove or add class
f(this, 'good');
}
rep_x.oninput = function(){
let f = this.value.match(/^[1-9][0-9]*$/) ? aC : rC;
f(this, 'good');
}
rep_it.onclick = ()=>{
out.textContent = allGood(goods) ? rep_text.value.repeat(+rep_x.value) : '';
// out.scrollIntoView(); // use this but it's a Stack Overflow issue
}
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; color:#fff; padding:0; margin:0; outline:none; -moz-user-select:none; -ms-user-select:none; -webkit-user-select:none; user-select:none; overflow:hidden;
}
html,body,.main{
width:100%; height:100%;
}
.main{
background:#333; padding:5px; overflow:auto;
}
.main *{
font:bold 22px Tahoma, Geneva, sans-serif;
}
label>span{
cursor:pointer; display:inline-block; height:27px; text-shadow:-1px 0 #000,0 1px #000,1px 0 #000,0 -1px #000; float:left;
}
input[type=text],input[type=number]{
width:100%; height:38px; background:#fff; color:#000; border-radius:3px; border:1px solid #c00; padding:5px; margin:3px 0; box-shadow:none; -moz-user-select:text; -ms-user-select:text; -webkit-user-select:text; user-select:text;
}
input[type=button],button{
cursor:pointer; width:100%; background:linear-gradient(#1b7bbb,#147); color:#fff; font:bold 28px Tahoma, Geneva, sans-serif; padding:5px; border:1px solid #007; border-radius:10px; margin-top:7px;
}
input.good{
border-color:#0c0;
}
#output{
color:#aaf; margin:5px 10px; text-overflow:ellipsis;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<label><span>Text to Repeat</span><input id='rep_text' type='text' value='' /></label>
<label><span>Times to Repeat</span><input class='good' id='rep_x' type='number' value='1' min='1' /></label>
<input id='rep_it' type='button' value='REPEAT' />
<div id='output'></div>
</div>
</body>
</html>

Not able to execute a condition statement in javascript

I want to display a background image in the background depending on the current weather condition.When I write the following lines in my javascript the code seems to fail:
if(ftemp>=0){
document.body.style.backgroundImage =
"url('https://images.pexels.com/photos/412462/pexels-photo-412462.jpeg?w=940&h=650&auto=compress&cs=tinysrgb')";
}
I am getting the data(ftemp) from an API call and using the condition statement displaying the respective background image.
I tried running just this
document.body.style.backgroundImage =
"url('https://images.pexels.com/photos/412462/pexels-photo-412462.jpeg?w=940&h=650&auto=compress&cs=tinysrgb')";
and the code runs.I believe that there is some problem with the if statement.
Here is the link to my work if it helps:
https://codepen.io/ryoko1/pen/eRvxKb?editors=0110
Thanks.
You are trying to use ftemp variable before getting the value from API. to solve this issue you can access ftemp variable inside getJSON.
Here is you working code: https://codepen.io/dineshu07/pen/ZyvpMP
$(document).ready(function() {
var lat, long, ftemp, ctemp;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
var url ="https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/ff2765ec67506dd69b7c42209bb40d7d/" +
lat +
"," +
long;
$.getJSON(url, function(data) {
var type = data.timezone;
ftemp = data.currently.temperature;
var icon = data.currently.summary;
$("#data").html(ftemp + " &#8457");
$("#temp").html(type);
$("#time").html(icon);
if(ftemp>=0){
document.body.style.backgroundImage = "url('https://images.pexels.com/photos/412462/pexels-photo-412462.jpeg?w=940&h=650&auto=compress&cs=tinysrgb')";
}
}).catch(function(error) {
console.error(error);
});
});
}
$("#butt1").click(function() {
ctemp = ftemp - 32;
ctemp *= 0.5556;
ctemp = Math.round(ctemp * 100) / 100;
$("#data").html(ctemp + " &#8451");
});
$("#butt2").click(function() {
ftemp = Math.round(ftemp * 100) / 100;
$("#data").html(ftemp + " &#8457");
});
});
$("button").show();
p{
font-size:20px;
text-align:center;
}
h1{
text-align:center;
}
#dat{
position:absolute;
width:230px;
height:250px;
left:47%;
top:47%;
margin-left:-50px;
margin-top:-50px;
font-size:20px;
background-color:black;
border-style:solid;
color:white;
}
#temp{
text-align:center;
}
#time{
text-align:center;
}
#data{
text-align:center;
}
button{
float:left;
display:none;
text-align:center;
color:#FF4A4A;
background-color:
}
#butt1{
margin:5px;
}
#butt2{
margin:5px;
}
body{
background-size:cover;
background-repeat:no repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><u>Weather App</u></h1>
<div id="dat">
<p id="data">
</p><br>
<p id="temp">
</p><br>
<p id="time">
</p>
<button id="butt1">imperial
</button>
<button id="butt2">metric
</button>
</div>
Your ftemp is undefined. If you need to check a variable value, try this
console.log(variable)

Toggle changes css selectors

I'm trying for not to change the id property of a paragraph on button click. That first part works. But when the button is clicked again should revert to the original styling. New with JavaScript so any other helpful articles would be great.
Here is the css:
<style type="text/css">
#attention
{
font-size:24px;
background-color:yellow;
width:300px;
}
#normal
{
background-color:white;
font-size:12px;
}
</style>
JS
function changeText() {
var text = document.getElementById("textChange");
text.innerHTML = "New Text";
text.id = "attention";
}
HTML
<div>
<p id="textChange">Some generic text here</p>
<input id="Button1" type="button" value="Do Something" onclick="changeText();" />
</div>
You should use classes for this type of functionality. For example like this:
function changeText() {
var text = document.getElementById("textChange");
text.innerHTML = "New Text";
text.className = text.className == "attention" ? 'normal' : 'attention';
}
So CSS becomes:
.attention {
font-size:24px;
background-color:yellow;
width:300px;
}
.normal {
background-color:white;
font-size:12px;
}
Demo: http://jsfiddle.net/5yx44/
First do not change the ID of the element.
Toggle a class instead.
Do not use inline event attributes. Use DOM3 listeners instead.
CSS
<style type="text/css">
.attention
{
font-size:24px;
background-color:yellow;
width:300px;
}
.normal
{
background-color:white;
font-size:12px;
}
</style>
HTML
<div>
<p id="textChange">Some generic text here</p>
<input id="Button1" type="button" value="Do Something" />
</div>
JS
var btn = document.getElementById('Button1');
btn.addEventListener('click', function() {
var div = document.getElementById('textChange');
div.className = 'attention';
});

how can I dynamically resize an html textbox to avoid overflowing?

I would like to know how to resize a textbox to prevent text nearby it from overflowing.
I have 3 elements in a row, a label, a text box, and a button. the label however, can have words of varying lengths. if the word is too long it will move the text input too far to the side and the button will overflow onto the next line. to preserve the style of the page, I would prefer that the button stays on the same line as the other 2 elements.
I am trying to get the text box to shrink only as much as necessary to allow room for the other elements.
can I do this with JQuery?
Edit: here's the JFiddle thing:
http://jsfiddle.net/425ve/2/
and here's the main code:
<html>
<head>
<style>
body{
background-color:#000000;
color:#cccccc;
}
#chatbox{
width:100%;
height:85%;
border-style:solid;
border-color:#000000;
overflow:auto;
}
#mainchat{
width:82%;
float:left;
margin:0;
}
#sidebar{
float:left;
height:97%;
width:17%;
border-style:dashed;
border-width:1px;
border-color:#AAAAAA;
border-right:0;
border-top:0;
border-bottom:0;
overflow:auto;
}
#topbar{
border-style:dashed;
border-width:1px;
border-color:#AAAAAA;
border-left: 0;
border-top: 0;
float:left;
width:82%;
}
a{
color:#cccccc;
text-decoration:none;
}
a:hover{
color:#CCCCEE;
background-color:111122;
}
#topbarname{
float:right;
}
#message{
width: 90%;
background-color:#000000;
border-color:#CCCCCC;
border-style:solid;
border-width: 1px;
color:CCCCCC;
}
#submitbutton{
background-color:#000000;
border-color:#CCCCCC;
border-style:solid;
border-width: 1px;
color:#CCCCCC;
}
</style>
<script>
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return unescape(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("IceID");
if (myCookie == null) {
window.location="login.php"
}
else {
// do cookie exists stuff
}
}
doSomething();
</script>
</head>
<body>
<div id="topbar">
| Information | Logs | characters | Profile | Private logs | Messages | Logout |
</div>
<div id="mainchat">
<div id="chatbox">
<?php
include("getpost.php");
//improve this with AJAX!
?>
</div>
<div id="input">
<form id="inputchat">
<b id="name">
<?php
echo $_COOKIE['IceID'];
?>
</b>
<input type="text" name="message" id="message"></input>
<input type="submit" id="submitbutton" value="say"></input>
</form>
</div>
<div id="utools">
</div>
</div>
<div id="sidebar">
<div id="title">
A
</div>
<div id="list">
</div>
</div>
</body>
</html>
Edit:to clarify, the name doesn't actively change while the page is being used(only right before being displayed), but it will be different depending on who loads the page. their username fits into that label.
You don't need jQuery. jQuery could make it much simpler though. I prefer vanilla.
var left = document.getElementById('name')
var resizable = document.getElementById('message')
var right = document.getElementById('submitbutton')
realign()
window.addEventListener('resize', realign)
function realign() {
resizable.style.width = '0'
var extraWidth = getWidth(resizable) // Measure the border and padding on it's own.
resizable.style.width = getWidth(resizable.parentNode) - getWidth(left) - getWidth(right)
function getWidth(element) { // Superior to offsetWidth because it measures fractions of a pixel which is even more relevant when using the browser zoom feature.
var rect = element.getBoundingClientRect() // A accurate way to measure location on the screen.
return rect.right - rec.left // The accurate width.
}
}
The only adjustment you need would be to fix my typo(s) if I made any and then if you want to support older versions of IE, you need to use the alternative to addEventListener, Google it.

jQuery custom functions with .data and html5 data atributes

I am trying to append a new "app" to my "AppList" when a button is clicked.
JS
$(".appCreate" ).click(newApp);
function newApp() {
var facebookTemp = $("#facebook-template").html();
var appName = $(this).data("appName");
var appSize = $(this).data("appSize");
var appTemp = $(this).data("appTemp");
$("<div class=\"app" + appName + appSize + "\"></div>").html(appTemp).appendTo(".AppList");
};
HTML
<body>
<section id="AppBox">
<div class="AppList">
<!-- == Facebook == -->
<div id="facebook-template">
<div class="App facebook Size170x290">
<h1>Hello Test</h1>
</div>
</div>
</div>
</section>
<!-- == Settings == -->
<section id="dialog-settings" class="dialog" title="Settings">
<button data-appName="facebook" data-appSize="Size170x290" data-appTemp="facebookTemp" class="appCreate">
Facebook</button>
</section>
</body>
CSS
#facebook-template {
display: none;
}
.facebook {
background:linear-gradient(to bottom, #133783 0px, #102E6D 100%) repeat scroll 0 0 #133783;
}
.facebook { top:120px; left:0; }
#AppBox {
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
margin:0;
}
.AppList {
position:absolute;
height:100%;
width:100%;
margin:0;
padding:0;
}
.App {
position:absolute;
display:block;
margin:5px;
padding:0;
box-shadow:0 0 5px 1px black;
color:#FFFFFF;
cursor:move;
}
.Size170x290 {height:170px;width:290px;}
Basically the thing isn't showing up and i don't know whats causing it.
You lost the context of your click handler.
This was an obvious first mistake:
$(".appCreate" ).click(newApp);
Second mistake is data names. Change to:
var appName = $(this).data("appname");
Notice the case. Convert all names to lower case.
I also added handlebars.js because of the conversation in the comments.
New working code:
$(".appCreate" ).click(newApp);
function newApp() {
var facebookTemp = $("#facebook-template").html();
var appName = $(this).data("appname");
var appSize = $(this).data("appsize");
var appTemp = $(this).data("apptemp");
var template = Handlebars.compile(facebookTemp);
var html = template({
app : appName,
facebook : appTemp,
size : appSize
});
$(".AppList").append(html);
};
Live DEMO && CODE.

Categories

Resources