I'm working on my first ever JavaScript project (a palindrome checker) and I'm kind of getting stuck. I've learned about localStorage() but I can't seem to implement it in my own project. It'd be awesome if someone could point me in the right direction, or write pseudo code as to what I should do to get it to work. I really want to solve it myself, but a little help is much needed here. Thanks :). My JavaScript code (and HTML and CSS for reference:
Edit: I want to show the results (each on a separate line) on the screen using localStorage() and use it again to enable the user to delete the results when clicking on the button.
const checkBtn = document.getElementById("check-word");
const clearBtn = document.getElementById("clear-history");
const outputField = document.getElementById("word-checked");
let array = [];
checkBtn.addEventListener("click", () => {
const str = document.getElementById("input").value;
array = [...array, str];
console.log(array);
palindrome(str);
renderResult();
function palindrome(str) {
const lettersOnly = str.toLowerCase().match(/[a-z0-9]/g);
return lettersOnly.join("") === lettersOnly.reverse().join("");
}
renderResult();
function renderResult() {
if (palindrome(str) === true) {
outputMessage = `︎✔︎ '${str}' is a palindrome!`
} else {
outputMessage = `𐄂 '${str}' is not a palindrome!`
}
outputField.textContent = outputMessage;
}
document.getElementById("input").value = ""; // clear input field after clicking on checkBtn
})
// clearBtn.addEventListener("click", () => {
// localStorage.clear();
// array = [];
// // render again!
// })
* {
background-color: #121212;
font-size: 16px;
margin: 0;
padding: 0;
}
h1 {
font-family: "VT323", monospace;
font-size: 5rem;
color: #CE1212;
text-align: center;
margin-top: 50px;
}
.container {
font-family: "Nanum Gothic Coding", monospace;
color: white;
width: 75%;
height: 62.5vh;
margin: 25px auto 25px auto;
/* border: 2.5px solid; */
border-color: white;
padding: 15px;
}
.input {
margin-left: 25px;
}
.input-field {
margin-left: 25px;
margin-top: 12.5px;
padding: 7.5px;
font-family: "Nanum Gothic Coding", monospace;
color: white;
border: 1px solid;
}
.input-field:focus::placeholder {
color: transparent;
}
.check-word, .clear-history {
padding: 7.5px;
font-family: "Nanum Gothic Coding", monospace;
color: white;
border: 1px solid;
border-color: white;
cursor: pointer;
}
.check-word:hover, .clear-history:hover {
color: #CE1212;
}
.child-1 {
margin-top: 50px;
margin-left: 25px;
/* border: 1px solid; */
padding: 15px;
}
#word-checked {
margin-top: 15px;
}
.footer {
font-family: "Nanum Gothic coding", monospace;
color: white;
text-align: center;
margin-bottom: 25px;
}
a:link, a:visited {
color: white;
text-decoration: none;
}
a:hover, a:active {
color: #CE1212;
text-decoration: underline;
}
/*
top, right, bottom, left
*/
<!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>Palindrome Checker</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nanum+Gothic+Coding&family=VT323&display=swap" rel="stylesheet">
<link rel="stylesheet" href="index.css">
</head>
<body>
<main>
<h1>🌮 Palindrome Checker 🐱</h1>
<div class="container">
<label for="input" class="input">Type a word or phrase</label>
<br>
<input type="text" name="input" class="input-field" id="input" placeholder="Type something...">
<button type="button" class="check-word" id="check-word">Check word</button>
<button type="button" class="clear-history" id="clear-history">Clear history</button>
<div class="child-1">
<p id="word-checked">Results will be shown here!</p>
</div>
</div>
</main>
<footer class="footer">
<p>Built by Yin Chu</p>
</footer>
<script src="index.js"></script>
</body>
</html>
It's really easy. (At least much easier than cookies)
localStorage.setItem('key', 'value'); // to store data
var myData = localStorage.getItem('key') // to get data
localStorage.removeItem('key') // to remove one data
localStorage.clear() // to remove all data
Replace key and value with the data key and the data to store respectively.
Related
I'm trying to use the value that each book has on its "status" and make the function "changeStatus()" run but "book.status" is defined inside a function, how can I get it? or is there any other way i can change the button behavior on click? I tried using a querySelector but it only allows me to click one button per refresh
let books = [];
const $name = document.querySelector("#name");
const $author = document.querySelector("#author");
const $status = document.querySelector("#status");
const $pages = document.querySelector("#pages");
const $tableBody = document.querySelector("#book-table-body");
function addBookToTable() {
// checkLocalStorage();
$tableBody.innerHTML = "";
books.forEach((book) => {
const htmlBook = `
<tr>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.pages}</td>
<td><button class="status-button" onclick="changeStatus()">${book.status}</button></td>
<td><button class="delete">delete</button></td>
</tr>
`;
$tableBody.insertAdjacentHTML("afterbegin", htmlBook);
});
}
function changeStatus(){
}
const addBook = (event) => {
event.preventDefault();
let book = {
title: $("#title").val(),
author: $("#author").val(),
pages: $("#pages").val(),
status: $("#status").val(),
};
const cb = document.querySelector("#status");
if (cb.checked === true) {
book.status = "read";
} else {
book.status = "not read";
}
books.push(book);
document.forms[0].reset();
// Update DOM
addBookToTable(book);
const deleteBtn = document.querySelector(".delete");
deleteBtn.addEventListener("click", function deleteBook(){
books.splice(books.indexOf(book), 1);
addBookToTable(book);
})
// const myBtn = document.querySelector(".status-button");
// myBtn.addEventListener('click', function changeStatus(){
// if (book.status === "read"){
// myBtn.innerHTML="not read"
// book.status = "not read"
// }
// else if(book.status === "not read"){
// myBtn.innerHTML = "read";
// book.status = "read"
// }
// }
// );
localStorage.setItem("myMangaList", JSON.stringify(books));
};
function popForm() {
$("#popup").removeClass("hide");
}
function minimizeForm(){
$("#popup").addClass("hide");
}
function hideForm() {
$("#popup").addClass("hide");
$("#main-page").removeClass("hide");
}
function toggle() {
$("#main-page").addClass("hide");
}
* {
font-family: 'Lato', sans-serif;
text-align: center;
/* background-image: url(./images/image.jpg);
background-position: bottom;
background-size: cover; */
}
.hide {
display: none;
}
.hide-form {
background-color: transparent;
color: white;
border: none;
cursor: pointer;
font-size: 1.5rem;
margin-top: 20px;
margin-right: 15px;
position: absolute;
top: 0;
right: 0;
}
h1 {
font-size: 2.5rem;
font-weight: 900;
font-family: 'Work Sans', sans-serif;
}
h1 span {
color: #48abe0;
}
table {
border-collapse: collapse;
width: 100%;
}
td,
th {
/* border: 1px solid #dddddd; */
text-align: center;
padding: 8px;
}
#main-page {
margin-right: 80px;
margin-left: 80px;
}
#addBook {
border-radius: 70%;
background-color: #48abe0;
color: white;
border: none;
padding: 5px;
font-size: 31px;
height: 65px;
width: 65px;
box-shadow: 0 2px 4px darkslategray;
cursor: pointer;
transition: all 0.2s ease;
position: fixed;
bottom: 25px;
right: 25px;
}
#popup {
/* display: flex; */
justify-content: center;
align-items: center;
flex-direction: column;
gap: 30px;
padding-top: 50px;
padding-bottom: 50px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px;
background: #48abe0;
border-radius: 10px;
}
#popup input {
width: 80%;
padding: 15px;
margin-top: 25px;
border: 1px solid;
border-radius: 5px;
outline: none;
color: white;
font-weight: bold;
font-size: 1em;
background: #48abe0;
}
.status-box {
margin-top: 25px;
}
<!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">
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css">
<!-- fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Edu+NSW+ACT+Foundation:wght#500&family=Edu+QLD+Beginner:wght#400;600;700&family=Edu+TAS+Beginner:wght#700&family=Josefin+Sans:wght#300&family=Lato&family=Montserrat:wght#100;600&family=Mouse+Memoirs&family=Poppins:ital,wght#0,500;1,200&family=Quicksand:wght#300&family=Ubuntu:wght#300&family=Work+Sans:wght#200&display=swap"
rel="stylesheet">
<title>Library</title>
</head>
<body>
<h1>My <span>Manga</span> Library</h1>
<div id="popup" class="hide">
<form>
<button class="hide-form" onclick=" minimizeForm()">X</button>
<!-- <label for="title">Manga Title:</label> -->
<input type="text" id="title" placeholder="Title eg: One Piece"> <br>
<!-- <label for="author">Author:</label> -->
<input type="text" id="author" placeholder="Author eg: Eichiro Oda"><br>
<!-- <label for="pages">Pages:</label> -->
<input type="text" id="pages" placeholder="Pages eg: 2000"><br>
<div class="status-box">
<label for="status">Read the book</label>
<input type="checkbox" id="status" name="status" value="">
</div>
<button type="submit" id="submit" onclick="addBook(event); hideForm()">Submit</button>
</form>
</div>
<!-- onclick="addBook() -->
<div id="main-page">
<h1>list</h1>
<div id="books-grid">
<table id="di-books">
<tr>
<th>Name</th>
<th>Author</th>
<th>Pages</th>
<th>Status</th>
<th></th>
</tr>
<tbody id="book-table-body"></tbody>
</table>
</div>
<button id="addBook" onclick="popForm(); toggle()">+</button>
</div>
<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
If you want to update the status of a book, you need a way to identify each book uniquely. Although it is possible to do this based on e.g. title or author, the reality is that those fields are not guaranteed to be unique.
Typically, you'd use the Id number of a database entry, but since you're using mock data that isn't realy an option here. We could e.g. use a UUID though:
let book = {
title: $("#title").val(),
author: $("#author").val(),
pages: $("#pages").val(),
status: $("#status").val(),
id: self.crypto.randomUUID() //Warning: might only work with HTTPS sites. Implement your own unique id in any way you please.
};
Now we have a unique id, we can use it to couple each status button with a unique book entry. Lets adjust the HTML:
const htmlBook = `
<tr>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.pages}</td>
<td><button class="status-button" onclick="changeStatus('${book.id}')">${book.status}</button></td>
<td><button class="delete">delete</button></td>
</tr>
`;
and lets write the update function:
function changeStatus(id){
//step 1: find our book with the matching unique id
let book = books.filter(book => book.id === id)[0];
//Step 2: update the book its status
if (book.status === "read"){
book.status = "not read";
}
else if(book.status === "not read"){
book.status = "read"
}
//Step 3: update our table with the new data.
addBookToTable();
};
And voila, we're able to switch the status of any book!
I tried to stick as close to your code as possible so you'd better understand it, but a lot more improvements can be implemented, such as event listeners instead of explicitly calling the changeStatus function, but I'll leave that as an exercise to you.
Full working example:
codepen
I am currently learning how to work with API's (fetch specifically) and I fetched all the data onto the screen. Now I am trying to figure out how to implement a search bar but I can't figure it out. Would it be easier to use a framework like React? I will take all feedback, I am here to learn.
let elements = document.querySelector(".elements");
let dataaa = document.querySelector(".dataaa");
let searchbar = document.getElementById("searchbar");
// SEARCH FILTER
searchbar.addEventListener("keyup", (e) => {
// HELP HERE
console.log(e.target.value)
});
function getdata() {
fetch(
`https://data.messari.io/api/v1/assets?fields=id,slug,symbol,metrics/market_data/price_usd`
)
.then((response) => {
const data = response.json();
return data;
})
.then((data) => {
const html = data.data
.map((pieceofdata) => {
const name = pieceofdata.slug;
const symbol = pieceofdata.symbol;
const price = +pieceofdata.metrics.market_data.price_usd.toFixed(2);
return `<div class="pieceofdata"><h1 class= "symbol"> ${symbol}</h1><h1 class= "name"> ${name}</h1><h1 class= "price"> $${price}</h1>
</div>`;
})
.join(" ");
dataaa.innerHTML = html;
// console.log(data)
// console.log(html)
});
}
getdata();
* {
padding: 0;
margin: 0;
box-sizing: border-box;
color: white;
}
body {
background-color: #1a1a1a;
overflow-x: hidden;
}
.title {
text-align: center;
font-size: 4rem;
margin-bottom: 2em;
margin-top: 0.5em;
}
#searchbar {
margin-left: 80%;
margin-bottom: 5em;
background-color: #1a1a1a;
outline: none;
border: white solid 1px;
padding: 1em;
color: white;
font-size: 1rem;
font-weight: bold;
}
::placeholder {
color: white;
font-size: 1rem;
font-weight: bold;
}
.dataaa {
display: flex;
flex-direction: column;
}
.pieceofdata {
width: 100vw;
border: 2px rgb(0, 255, 136) solid;
display: flex;
padding: 1em 0em;
justify-content: space-around;
}
.subtitles {
display: flex;
width: 100vw;
justify-content: space-around;
}
li {
list-style: none;
font-size: 2rem;
font-weight: bold;
margin-bottom: 0.8em;
border-bottom: 2px solid rgb(0, 255, 136);
}
.symbol {
color: lime;
font-size: 2.5rem;
}
.name {
justify-self: normal;
}
.price {}
<!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">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<h1 class="title">Crytpo Currencies</h1>
</div>
<form action=""><input placeholder="Search for Crypto" type="text" name="searchbar" id="searchbar"></form>
<ul class="subtitles">
<li class="symbol-title">Symbol</li>
<li class="name-title">Name</li>
<li class="price-title">Price</li>
</ul>
<div class="dataaa">
</body>
<script src="main.js"></script>
</html>
Basically, you want to create a filter with vanilla js. (as you said yourself it might be easier to do so with the help of React or Vue)
but what you can do here is to store your data in an array say like responseData in the global script. and also another one for your filtered data. say filteredData.
then after each time the user types in a letter and your eventListener is called:
var reg = new RegExp(event.target.value, 'g');
filteredData = responseData.filter(item => item.{{name}}.match(reg))
in {{name}} you should put what you are actually looking for.
and then you can render the page based on the filteredData array.
All you need to know is the built-in filter function of Javascript and the usage of match I supose.
Im no expert (started learning recently) but put the onChange function on search bar and try this
if(pieceofdata.slug.includes(event.target.value)){
...your code and variables;
return `<div class="pieceofdata"><h1 class= "symbol"> ${symbol}</h1><h1 class= "name"> ${name}</h1><h1 class= "price"> $${price}</h1>
</div>`;
}
it basically compares what you are writing in the search bar and comparing it to the names of "piece of information".
or you could also use filter method for arrays to find the desired element in that array.
I have an HTML page, and I have a <textarea> element in it. Let's also say I have a send button that displays the message on the screen. When multiple messages are sent, their position will move to below the previous message sent. New messages will be in separate containers (I made borders). I've used this code that worked. Actually, it didn't completely work. When you enter multiple messages, instead of creating a new message border with the message inside it, it puts all your text in the same element.
const button = document.getElementById("sendButton");
button.addEventListener("click", displayText);
function displayText() {
const display = document.getElementById("msg");
const textArea = document.getElementById("enterMsg");
display.append(
textArea.value,
document.createElement("br")
);
textArea.value = "";
}
body {
background-color: skyblue;
font-weight: bolder;
}
#enterMsg {
margin-top: 34%;
height: 130px;
width: 100%;
font-family: Arial, sans-serif;
font-size: 15px;
color: darkorange;
background-color: #d796ff;
font-weight: bolder;
}
.enterText {
font-family: Arial, sans-serif;
font-size: 15px;
color: darkorange;
background-color: #d796ff;
font-weight: bolder;
}
#sendButton {
margin-left: 96%;
}
#msg {
margin-left: 80%;
border: solid;
border-color: #b19cd9;
background-color: #b4ff94;
border-radius: 50px;
color: darkorange;
}
.extraSpace {
padding: 5px;
}
textarea::placeholder {
color: darkorange;
}
div.centered {
text-align: center;
border: solid;
border-color: blue;
margin-top: 10%;
margin-bottom: 10%;
}
.confirmButton {
text-align: center;
margin-bottom: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Main Page</title>
<link rel="stylesheet" href="style.css">
<script src="tools.js"></script>
</head>
<body>
<p id="msg" class="extraSpace"></p>
<textarea id="enterMsg" placeholder="Enter your message here..."></textarea>
<button id="sendButton" onclick="displayText('msg', 'enterMsg')">Send</button>
</body>
</html>
As I said, this code works but it puts all messages in a single element. Is there any way to make it so that a new border appears with the entered text inside it instead of putting every message into a single element?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Main Page</title>
<link rel="stylesheet" href="style.css">
<script src="tools.js"></script>
</head>
<body>
<div id="messages"></div>
<textarea id="enterMsg" placeholder="Enter your message here..."></textarea>
<button id="sendButton" onclick="displayText('msg', 'enterMsg')">Send</button>
</body>
</html>
const button = document.getElementById("sendButton");
button.addEventListener("click", displayText);
const textArea = document.getElementById("enterMsg");
const container = document.getElementById("messages");
function displayText() {
// Create a new element with the message as it's inner text.
const message = document.createElement("p");
message.innerText = textArea.value;
message.setAttribute("class", "msg");
// Add that to the document
container.appendChild(message);
textArea.value = "";
}
You'll also have to change your stylesheet because msg is a class now rather than an ID (since there will be more than one of them
I'm new to web programming and was hoping to create a system that randomly selects which students are enforced a backpack revision
Recently a student threatened to shoot up the school, it's been 1 month since that event, so the school instead of conducting a search on all students decided to make it totally random, so I decided to create a webpage that does just that.
However, old people will be using it, and although I sorted some of the code out, I wanted to make the website's background red if a revision is due, and green if the outcome of the randomizing algorithm equals a pass.
Here's my code so far:
HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SELEC</title>
<link rel="stylesheet" href="quote.css">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,700' rel='stylesheet' type='text/css'>
<script src="jquery-1.11.2.min.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<h2>Random Student Selection System</h2>
<div id="quoteContainer">
<p></p>
<p id="quoteGenius"></p>
</div><!--end quoteContainer-->
<div id="buttonContainer">
GEN
</div><!--end buttonContainer-->
</div><!--end container-->
</body>
</html>
JS:
$(document).ready(function(){
var quoteSource=[
{
quote: "PASS",
name:"PASS"
},
{
quote:"REVISION",
name:"REVISION"
},
];
$('#quoteButton').click(function(evt){
//define the containers of the info we target
var quote = $('#quoteContainer p').text();
var quoteGenius = $('#quoteGenius').text();
//prevent browser's default action
evt.preventDefault();
//getting a new random number to attach to a quote and setting a limit
var sourceLength = quoteSource.length;
var randomNumber= Math.floor(Math.random()*sourceLength);
//set a new quote
for(i=0;i<=sourceLength;i+=1){
var newQuoteText = quoteSource[randomNumber].quote;
var newQuoteGenius = quoteSource[randomNumber].name;
//console.log(newQuoteText,newQuoteGenius);
var timeAnimation = 100;
var quoteContainer = $('#quoteContainer');
//fade out animation with callback
quoteContainer.fadeOut(timeAnimation, function(){
quoteContainer.html('');
quoteContainer.append('<p>'+newQuoteText+'</p>'+'<p id="quoteGenius">'+'- '+newQuoteGenius+'</p>');
//fadein animation.
quoteContainer.fadeIn(timeAnimation);
});
break;
};//end for loop
});//end quoteButton function
});//end document ready
and CSS
body{
font-family: 'Roboto', sans-serif;
color: #000;
}
#container{
width:800px;
margin:50px auto;
padding: 20px;
width:50%;
}
#container h2{
text-align:center;
color:#045;
}
#quoteContainer{
width:75%;
background: #fff;
padding:10px;
margin:30px auto;
text-align: center;
height:70px;
}
#buttonContainer{
width: 100%;
text-align: center;
}
#quoteButton{
width:200px;
margin-top: 10px;
border:2px solid #E8450C;
color:#045;
font-family: inherit;
font-weight: bold;
padding:5px;
text-decoration: none;
text-align: center;
}
#quoteButton:hover{
cursor:pointer;
background:#E82B13;
color: #fff;
}
#quoteButton:active{
cursor: pointer;
}
#quoteButton{
display: inline-block;
}
#quoteGenius{
font-style: italic;
font-weight: 600;
text-align: center;
}
/*MEDIA QUERIES*/
#media screen and(max-width:760px){
#quoteButton,#addNew{
display: block;
}
}
I just started learning this last week.
Thanks in advance.
Regards.
Basically, first in your CSS you can make 2 classes, like .pass { background-color: green; } and .revision { background-color: red; } and then in your javascript, test the result of the random generator, and if the result is "pass" then add the class .pass to your <body> element, other wise, if it's "revision", add the class .revision to your <body> element.
Here's modification to your code to make this happen: (Run code snippet)
$(document).ready(function(){
var quoteSource=[
{
quote: "PASS",
name:"PASS"
},
{
quote:"REVISION",
name:"REVISION"
},
];
$('#quoteButton').click(function(evt){
//define the containers of the info we target
var quote = $('#quoteContainer p').text();
var quoteGenius = $('#quoteGenius').text();
//prevent browser's default action
evt.preventDefault();
//getting a new random number to attach to a quote and setting a limit
var sourceLength = quoteSource.length;
var randomNumber= Math.floor(Math.random()*sourceLength);
//set a new quote
for(i=0;i<=sourceLength;i+=1){
var newQuoteText = quoteSource[randomNumber].quote;
var newQuoteGenius = quoteSource[randomNumber].name;
//console.log(newQuoteText,newQuoteGenius);
var timeAnimation = 100;
var quoteContainer = $('#quoteContainer');
//fade out animation with callback
quoteContainer.fadeOut(timeAnimation, function(){
// BACKGROUND COLOR LOGIC HERE
if (newQuoteText === 'PASS') {
document.body.className = 'pass';
} else {
document.body.className = 'revision';
}
quoteContainer.html('');
quoteContainer.append('<p>'+newQuoteText+'</p>'+'<p id="quoteGenius">'+'- '+newQuoteGenius+'</p>');
//fadein animation.
quoteContainer.fadeIn(timeAnimation);
});
break;
};//end for loop
});//end quoteButton function
});//end document ready
body{
font-family: 'Roboto', sans-serif;
color: #000;
transition: background-color 500ms ease;
}
#container{
width:800px;
margin:50px auto;
padding: 20px;
width:50%;
}
#container h2{
text-align:center;
color:#045;
}
#quoteContainer{
width:75%;
background: #fff;
padding:10px;
margin:30px auto;
text-align: center;
height:70px;
}
#buttonContainer{
width: 100%;
text-align: center;
}
#quoteButton{
width:200px;
margin-top: 10px;
border:2px solid #E8450C;
color:#045;
font-family: inherit;
font-weight: bold;
padding:5px;
text-decoration: none;
text-align: center;
}
#quoteButton:hover{
cursor:pointer;
background:#E82B13;
color: #fff;
}
#quoteButton:active{
cursor: pointer;
}
#quoteButton{
display: inline-block;
}
#quoteGenius{
font-style: italic;
font-weight: 600;
text-align: center;
}
/*MEDIA QUERIES*/
#media screen and(max-width:760px){
#quoteButton,#addNew{
display: block;
}
}
.pass {
background-color: green;
}
.revision {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<h2>Random Student Selection System</h2>
<div id="quoteContainer">
<p></p>
<p id="quoteGenius"></p>
</div><!--end quoteContainer-->
<div id="buttonContainer">
GEN
</div><!--end buttonContainer-->
</div><!--end container-->
here you go the full code yours and edited...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,700' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
body{
font-family: 'Roboto', sans-serif;
color: #000;
}
#container{
width:800px;
margin:50px auto;
padding: 20px;
width:50%;
}
#container h2{
text-align:center;
color:#045;
}
#quoteContainer{
width:75%;
background: #fff;
padding:10px;
margin:30px auto;
text-align: center;
height:70px;
}
#buttonContainer{
width: 100%;
text-align: center;
}
#quoteButton{
width:200px;
margin-top: 10px;
border:2px solid #E8450C;
color:#045;
font-family: inherit;
font-weight: bold;
padding:5px;
text-decoration: none;
text-align: center;
}
#quoteButton:hover{
cursor:pointer;
background:#E82B13;
color: #fff;
}
#quoteButton:active{
cursor: pointer;
}
#quoteButton{
display: inline-block;
}
#quoteGenius{
font-style: italic;
font-weight: 600;
text-align: center;
}
/*MEDIA QUERIES*/
#media screen and(max-width:760px){
#quoteButton,#addNew{
display: block;
}
}
</style>
<title>Document</title>
</head>
<body>
<div id="container">
<h2>Random Student Selection System</h2>
<div id="quoteContainer">
<p></p>
<p id="quoteGenius"></p>
</div><!--end quoteContainer-->
<div id="buttonContainer">
GEN
</div><!--end buttonContainer-->
</div><!--end container-->
<script>
$(document).ready(function(){
var quoteSource=[
{
quote: "PASS",
name:"PASS"
},
{
quote:"REVISION",
name:"REVISION"
},
];
$('#quoteButton').click(function(evt){
//define the containers of the info we target
var quote = $('#quoteContainer p').text();
var quoteGenius = $('#quoteGenius').text();
//prevent browser's default action
evt.preventDefault();
//getting a new random number to attach to a quote and setting a limit
var sourceLength = quoteSource.length;
var randomNumber= Math.floor(Math.random()*sourceLength);
//set a new quote
for(i=0;i<=sourceLength;i+=1){
var newQuoteText = quoteSource[randomNumber].quote;
var newQuoteGenius = quoteSource[randomNumber].name;
// console.log(newQuoteText,newQuoteGenius);
//change the color of the page body
if(newQuoteText =="PASS"){
document.body.style.backgroundColor = "green";
}
if(newQuoteText =="REVISION"){
document.body.style.backgroundColor = "red";
}
var timeAnimation = 100;
var quoteContainer = $('#quoteContainer');
//fade out animation with callback
quoteContainer.fadeOut(timeAnimation, function(){
quoteContainer.html('');
quoteContainer.append('<p>'+newQuoteText+'</p>'+'<p id="quoteGenius">'+'- '+newQuoteGenius+'</p>');
//fadein animation.
quoteContainer.fadeIn(timeAnimation);
});
break;
};//end for loop
});//end quoteButton function
});//end document ready
</script>
</body>
</html>
In the following code, I am allowing users to edit text content, save and recall changes from own "local storage". So every editor's browser "remembers" their own editing, and each editor sees his changes only. I want to realise an idea of the anonymous wiki and import every user edits and display the last one in the final HTML page.
function saveEdits() {
//get the editable element
var editElem = document.getElementById("edit");
//get the edited element content
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage.userEdits = userVersion;
//write a confirmation to the user
document.getElementById("update").innerHTML = "Готово";
}
function checkEdits() {
//find out if the user has previously saved edits
if (localStorage.userEdits !== null)
document.getElementById("edit").innerHTML = localStorage.userEdits;
}
body {
display: block;
padding: 50px;
margin: 50px;
width: 90%;
font-family: 'Oranienbaum', serif;
font-size: 30px;
margin-right: 50px;
height: 90%
}
#edit {
background-color: white;
margin: 5px;
padding: 0px;
text-align: inherit;
font-size: 40px;
font-family: 'Oranienbaum', serif;
}
#button {
background-color: silver;
border: none;
top: 100px;
margin: 5px;
padding: 10px;
font-family: 'Oranienbaum', serif;
font-size: 20px;
}
#update {
background-color: white;
top: 100px;
margin: 5px;
padding: 5px;
font-size: 20px;
}
hr {
display: block;
margin-left: auto;
margin-right: auto;
border-style: dashed;
border-width: 1px;
}
.footer {
background-color: inherit;
top: 100px;
margin: 5px;
padding: 5px;
font-size: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Indexmod Encyclopedia — anonymous real-time editing </title>
<script src="code.js" type="text/javascript" charset="utf-8"></script>
<link href="style.css" rel="stylesheet" type="text/css">
<style>
#import url('https://fonts.googleapis.com/css?family=Oranienbaum');
</style>
</head>
<body onload="checkEdits()">
Indexmod Россия
<hr>
<div id="edit" contenteditable="true">
Here is Indexmod Encyclopedia anonymous real-time editing sandbox area
</div>
<hr>
<input type="button" id=button value="Сохранить" onclick="saveEdits()" />
<div id="update">Редактируй текст и нажми сохранить до следующего раза</div>
<p class="footer" id="footer"><span><script src="footer.js"></script></span>
</p>
</body>
</html>
While you're going to set item on local storage, the method goes to:
localStorage.setItem('userEdits', userVersion);
And get item
localStorage.getItem('userEdits');
Hope it would be help, This works for me.
See the reference: http://www.w3schools.com/html/html5_webstorage.asp