I am trying to make a simple To-Do like application. I want the "Tasks" which I add to remain even after closing the window or at least after refreshing. I tried to achieve that using MongoDB but I couldn't.
I think a simpler way to achieve this is by using arrays but I am not able to understand how to do that.
Please suggest me some way to achieve the above results....
let div = document.getElementById('tasks');
let add = document.getElementById('add');
let newTask = document.getElementById('newTask');
let c = 0;
add.addEventListener("click", function () {
let cbox = document.createElement("input");
let d = document.createElement("div");
let newt = newTask.value;
newTask.value = null;
cbox.type = "checkbox";
cbox.id = "check";
div.append(d);
d.id = "nd";
d.append(cbox);
d.append(newt);
c += 1;
if (c === 12) {
add.disabled = true;
newTask.value = "Stack Overflow";
}
});
/* body {
background-color: #42f5f5
} */
.card {
margin: 0 auto;
float: none;
/* margin-bottom: 10px; */
/* border: none; */
/* background-color: rgb(248, 179, 88); */
}
.container {
margin-top: 2.5rem;
}
#title {
width: 200px;
border: none;
font-size: larger;
font-weight: bold;
}
#newTask {
width: 200px;
}
#add {
margin-top: 1rem;
}
#newTask {
margin-top: 1rem;
}
#plus {
font-family: Arial, Helvetica, sans-serif;
font-size: 15px;
}
#nd {
font-size: 20px;
margin-top: 5px;
margin-bottom: 10px;
}
#check {
margin-left: 20px;
height: 15px;
width: 15px;
margin-right: 10px;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="ToDo.css" rel="stylesheet">
<title>To-Do</title>
</head>
<body>
<div class="container">
<div class="card" style="width: 35rem;height: 42rem;">
<div class="card-body">
<p style="font-size: 2rem;font-weight: bold;">
<input type="text" class="form-control" id="title" placeholder="Title">
</p>
<p id="main">
<div id="tasks">
</div>
<form class="form-inline">
<div class="form-group mx-sm-3 mb-2">
<input type="text" class="form-control" id="newTask" autocomplete="off"
placeholder="Enter new task">
</div>
<button type="button" class="btn btn-primary mb-2" id="add">Add Task</button>
</form>
</p>
</div>
</div>
</div>
<script src="ToDo.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
You can use localStorage to save data in browser storage.
here's link to documentation for localStorage .
//to set data in local storage
localStorage.setItem('myCat', 'Tom')
//to get data from localStorage
const cat = localStorage.getItem('myCat');
//to remove data from localStorage
localStorage.removeItem('myCat');
//for object you can stringify them
var myObj = [{name:"test", time:"Date 2017-02-03T08:38:04.449Z"}];
localStorage.setItem('item', JSON.stringify(myObj));
//Then when you want to retrieve data, you need to parse the string to object again.
var getObj = JSON.parse(localStorage.getItem('item'));
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
Hello I am creating a game similar to Simon. Where a user has to memorize a random color generated by the random color generator. When a button is clicked it is supposed to play a sound. I am able to play all the sounds when I click the buttons. I created a function that recognizes when the enter key is pressed to start the game. The game generates a random color with a corresponding sound and the user is supposed to click the same color. I am getting a ERROR NOT FOUND sounds/undefined.mp3 and also a DOM Exception: no supported source was found. It seems not to be able to find the right file.
function nextSequence() {
level = level + 1;
randomNumber = Math.floor(Math.random * 4);
randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
console.log(gamePattern);
//$("#" + randomChosenColor).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
animatePress(randomChosenColor);
playSound(randomChosenColor);
// animatePress(randomChosenColor);
}
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
console.log(userClickedPattern);
playSound(userChosenColor);
animatePress(userChosenColor);
});
function playSound(variable) {
$("#" + variable).ready(function() {
var audio = new Audio("sounds/" + variable + ".mp3");
audio.play();
});
}
$(document).on('keypress', function(e) {
if(e.which == 13) {
var h1header = document.getElementById("level-started").innerHTML = "Level " + level;
nextSequence();
started = true;
}
});
h1 {
text-align: center;
margin-bottom: 5%;
font-family: "Ubuntu";
font-size: 3rem;
}
body {
text-align: center;
}
.container {
width: 50%;
margin: auto;
}
.btn {
display: inline-block;
width: 200px;
height: 200px;
border: 10px solid black;
border-radius: 6%;
margin: 25px;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
.pressed {
box-shadow: 0 0 20px white;
background-color: grey;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon Game</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=Montserrat:wght#400;900&family=Ubuntu:wght#300;400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="intro" id = "level-started">Press Enter Key to start </h1>
<div class="container">
<div class="row">
<div class="btn green" type="button" id="green">
</div>
<div class="btn red" type="button" id="red">
</div>
</div>
<div class="row">
<div class="btn yellow" type="button" id="yellow">
</div>
<div class="btn blue" type="button" id="blue">
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script type="text/javascript" src="index.js">
</script>
</body>
<footer>© Hello World </footer>
</html>
I am trying to query a cloned element in my dom and queryselector can not find it. Specifically #reply_form brings up nothing despite the id being used in the template. I've also tried ("#reply_form"+post_id) since I re id it at the bottom before pushing it to the dom and nothing. I'm all out of ideas.
Here is the code:
<template id="reply_template">
<div class="lk">
<img class="profile_image" />
<div>
<div class="user">
<div class="reply_author"></div>
<div class="reply-body"></div>
</div>
<div class="reply">
<div class="d-flex align-items-center">
<i id="upvote" class="fas fa-arrow-up hover"></i>
<span id="upvote_count_badge" class="badge bg-secondary"></span>
<i id="downvote" class="fas fa-arrow-down hover"></i>
</div>
<div class="reply_comment" id="reply">Reply</div>
<div id="post_award_modal" data-bs-toggle="modal" data-bs-target="#siteModal">
<i class="fas fa-award hover"></i>
</div>
</div>
<div id="vl" class="vl"></div>
<form id="reply_form" class="form-hidden">
<img class="profile_image"/>
<input class="cmt-reply" type="text" placeholder="Write a reply2"/>
</form>
<div id="reply_loader"><!--Nested Replies go here--></div>
</div>
</div>
</template>
<script>
function loadReplies(post_id, count) {
var reply_loader = document.querySelector('#reply_loader'+post_id)
var reply_template = document.querySelector('#reply_template');
if (count==0) {
fetch('/_load_replies?f='+post_id).then((response) => {
// Convert the response data to JSON
response.json().then((data) => {
for (var i = 0; i < data.length; i++) {
//add_post(template, counter)
// Clone the HTML template
let template_clone = reply_template.content.cloneNode(true);
// Query & update the template content
let post_id=data[i].post_id;
let post_url=data[i].post_url;
let author=data[i].author;
let author_id=data[i].author_id;
let post_saved=data[i].current_user.post_saved;
let post_upvoted=data[i].current_user.post_upvoted;
let post_downvoted=data[i].current_user.post_downvoted;
let current_user=data[i].current_user.current_user;
let is_moderator=data[i].current_user.is_moderator;
let is_big_top_moderator=data[i].current_user.is_big_top_moderator;
let awards=data[i].awards;
let media_url=data[i].media_url;
let community=data[i].community;
profile_images=template_clone.querySelectorAll(".profile_image");
for(var k=0; k<profile_images.length; k++) {
profile_images[k].src=data[i].post_profile_image;
}
let top=data[i].author;
top+=" "+moment(data[i].timestamp).fromNow();
if (awards) {
top+=' ';
for(var key in awards) {
top+=awards[key]+' '+key;
}
}
if (post_upvoted) {
template_clone.querySelector("#upvote").setAttribute("style", "color: white");
template_clone.querySelector("#downvote").setAttribute("style", "color: gray");
} else if (post_downvoted) {
template_clone.querySelector("#upvote").setAttribute("style", "color: gray");
template_clone.querySelector("#downvote").setAttribute("style", "color: white");
} else {
template_clone.querySelector("#upvote").setAttribute("style", "color: gray");
template_clone.querySelector("#downvote").setAttribute("style", "color: gray");
}
template_clone.querySelector("#upvote").setAttribute("onclick", "vote("+post_id+",1)");
template_clone.querySelector("#downvote").setAttribute("onclick", "vote("+post_id+",0)");
template_clone.querySelector("#post_award_modal").setAttribute("onclick", "build_award_modal("+post_id+")");
template_clone.querySelector(".reply_author").innerHTML=top
template_clone.querySelector(".reply-body").innerHTML=data[i].body;
template_clone.querySelector("#upvote_count_badge").innerHTML=data[i].upvotes-data[i].downvotes;
//it finds #reply no problem
template_clone.querySelector("#reply").addEventListener("click", (e)=>{
e.target.classList.toggle("blue");
//It can not find this at all no matter what. I re id it at the bottom
console.log(template_clone.querySelector("#reply_form"+post_id))
template_clone.querySelector("#reply_form"+post_id).setAttribute("style", "color: blue")
template_clone.querySelector("#vl")
});
//re id
template_clone.querySelector("#upvote").id="upvote"+post_id;
template_clone.querySelector("#upvote_count_badge").id="upvote_count_badge"+post_id;
template_clone.querySelector("#downvote").id="downvote"+post_id;
template_clone.querySelector("#reply_loader").id="reply_loader"+post_id;
template_clone.querySelector("#reply").id="reply"+post_id;
template_clone.querySelector("#reply_form").id="reply_form"+post_id;
template_clone.querySelector("#vl").id="vl"+post_id;
reply_loader.appendChild(template_clone);
}
})
})
}
}
</script>
Here is a code snippet:
function open_form(post_id) {
console.log("reply"+post_id)
document.getElementById("#reply"+post_id).classList.toggle("blue")
document.getElementById("#reply_form"+post_id).classList.toggle("open")
document.getElementsByID("#vl"+post_id).classList.toggle("open");
}
.like-comment, .reply_comment{
cursor: pointer;
}
.vl{
border-left: 1px solid white;
border-bottom: 1px solid white;
border-bottom-left-radius: 30px;
width: 5%;
top: 25px;
position: absolute;
height: 100%;
left: -20px;
display: none;
}
.thumb.open, .vl.open, .form-hidden.open{
display: flex;
}
.form-hidden{
position: relative;
transform: translateX(35px);
display: none;
}
.profile_image{
width: 30px;
height: 30px;
border-radius: 50%;
}
.cmt-reply{
width: 75%;
height: 30px;
padding: 5px;
border-radius: 8px;
border: none;
margin-left: 5px;
}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.5.0/font/bootstrap-icons.css">
<link href="/static/css/style.css" rel="stylesheet">
<script src="https://js.stripe.com/v3/"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
</head>
<body>
<!--Broken Code here-->
<div class="reply_comment" id="reply64" onclick="open_form(64)">Reply</div>
<div id="vl64" class="vl"></div>
<form id="reply_form64" class="form-hidden">
<img class="profile_image" src="/avatars/1be25219994e4ef695e1c6f0d4d128ac_m.png">
<input class="cmt-reply" type="text" placeholder="Write a reply2">
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
</body>
When using getElementById you don't need to pass # in the string. check following snippet.
function open_form(post_id) {
console.log("reply" + post_id)
document.getElementById("reply" + post_id).classList.toggle("blue");
document.getElementById("reply_form" + post_id).classList.toggle("open");
document.getElementById("vl" + post_id).classList.toggle("open");
}
.like-comment,
.reply_comment {
cursor: pointer;
}
.vl {
border-left: 1px solid white;
border-bottom: 1px solid white;
border-bottom-left-radius: 30px;
width: 5%;
top: 25px;
position: absolute;
height: 100%;
left: -20px;
display: none;
}
.thumb.open,
.vl.open,
.form-hidden.open {
display: flex;
}
.form-hidden {
position: relative;
transform: translateX(35px);
display: none;
}
.profile_image {
width: 30px;
height: 30px;
border-radius: 50%;
}
.cmt-reply {
width: 75%;
height: 30px;
padding: 5px;
border-radius: 8px;
border: none;
margin-left: 5px;
}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.5.0/font/bootstrap-icons.css">
<link href="/static/css/style.css" rel="stylesheet">
<script src="https://js.stripe.com/v3/"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
</head>
<body>
<!--Broken Code here-->
<div class="reply_comment" id="reply64" onclick="open_form(64)">Reply</div>
<div id="vl64" class="vl"></div>
<form id="reply_form64" class="form-hidden">
<img class="profile_image" src="/avatars/1be25219994e4ef695e1c6f0d4d128ac_m.png">
<input class="cmt-reply" type="text" placeholder="Write a reply2">
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
</body>
Here is getElementById documentation on mdn.
Problem: My password generator will not work until I move my slider. However, I would like the value to default to 8. So if someone loads page, and clicks generate PW, a random pw of 8 would populate.
//generate a password function
function passwordGenerator () {
// Length of the password?
var passwordLength = document.getElementById('num').value;
// characters options for PW
const values = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()";
// defining password
var password = "";
// creating a loop to choose password
for (var i = 1; i <= passwordLength; i++) {
password = password + values.charAt(Math.floor(Math.random() * Math.floor(values.length -1)));
}
// adding the password to the content area
document.getElementById('display').value = password;
}
// adjust value when moving slider
function sliderMove(){
document.getElementById('num').value = document.getElementById('slider1').value;
document.getElementById('num').textContent = document.getElementById('num').value;
}
//copy to clipboard
function selectText() {
const input = document.getElementById('display');
input.focus();
input.select();
document.execCommand('copy')
}
.backgroundWhite {
background-color: white;
border: darkgray 2px solid;
padding-bottom: 25px;
}
.backgroundGray {
background-color: lightgray;
width: 100%;
height: 500%;
}
.passwordBox {
width: 500px;
height: 200px;
text-align: center;
}
body {
height: 100%;
background-color: lightgray;
}
.headText {
padding: 50px;
}
.buttonOnClick {
margin: 20px;
}
.passGenButton {
color: white;
background-color: red;
margin-right: 15%;
height: 40px;
border-radius: 12px;
}
.copyButton {
margin-left: 15%;
background-color: darkgray;
color: white;
height: 40px;
border-radius: 12px;
}
textarea {
padding: 20px;
font-size: 19px;
color: #4f4f4f;
}
.titleClass {
padding-top: 10px;
}
#media (max-width: 537px) {
.passGenButton {
color: white;
background-color: red;
margin-right: 1%;
height: 40px;
border-radius: 12px;
}
.copyButton {
margin-left: 1%;
background-color: darkgray;
color: white;
height: 40px;
border-radius: 12px;
}
.passwordBox {
width: 400px;
height: 200px;
text-align: center;
}
.backgroundWhite {
background-color: white;
border: darkgray 2px solid;
padding-bottom: 25px;
padding-left: 20px;
}
}
<!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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="app.js"></script>
<title>Random Password Generator</title>
</head>
<body>
<div class="conatiner backgroundGray">
<div class="row">
<div class="col-12">
<div class="topText">
<!-- Header -->
<h1 class="text-center text-dark headText">Password Generator</h1>
</div>
<div class="container">
<div class='row'>
<div class="col-lg-12 col-sm-12 text-center">
<div class="content backgroundWhite">
<!-- Sub Header -->
<h4 class="titleClass">Generate a Password</h4>
<br />
<!-- Slider -->
<div class="slidecontainer">
<p>Select PW Length</p>
<input id="slider1" type="range" min="8" max="128" value="8" onchange="sliderMove()"
class="robClass">
<span id="num">8</span>
</div>
<br />
<!-- Password Box -->
<textarea class="passwordBox" type="text" id="display"
placeholder="Your Secure Password"></textarea>
<br />
<button onclick="passwordGenerator()" class="passGenButton buttonOnClick">Generate
Password</button>
<button class="buttonOnClick copyButton" defaultValue="8" onclick="selectText()">Copy to
clipboard</button>
<div id='length'></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I have played with HTML and JS. I have tried to create a var num = 8;
no luck.
Does anyone have any ideas on how I can do this?
At the start of your passwordGenerator function:
var passwordLength = document.getElementById('num').value;
This element (<span id="num">8</span>) doesn't have a value attribute, so your function will try to generate a password with a length equal to undefined.
You should get the value from your slider instead:
var passwordLength = document.getElementById('slider1').value;
You can also simplify your function sliderMove function:
function sliderMove() {
document.getElementById('num').textContent = document.getElementById('slider1').value;
}
I am new to web development and currently learning jQuery from codecademy.
I made a simple opinion pull.
Problem: Besides add comment, i would like to delete the comment when i highlight the comment and press trash button.
index.html
<!doctype html>
<html>
<head>
<!--Boostrap CSs stylesheet-->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!--jQuery script-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!--Bootsrap js-->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!--CSS stylesheet-->
<link href="index.css" media="screen" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<textarea class="form-control status-box" rows="2" placeholder="What's on your mind?"></textarea>
</div>
</form>
<div class="button-group pull-right">
<p class="counter">140</p>
<div class= "glyphicon glyphicon-pencil" ></div>
<div class= "glyphicon glyphicon-trash" ></div>
</div>
<ul class="posts">
</ul>
</div>
<!--JavaScript script-->
<script src="index.js"></script>
</body>
</html>
index.css
html,body {
font-family: courier, sans-serif;
color: #404040;
background-color: #eee;
}
.container {
width: 520px;
margin-top: 20px;
}
.button-group {
margin-bottom: 20px;
padding: 5px;
}
.counter {
display: inline;
margin-top: 0;
margin-bottom: 0;
margin-right: 10px;
}
.posts {
clear: both;
list-style: none;
padding-left: 0;
width: 100%;
}
.posts li {
background-color: #fff;
border: 1px solid #d8d8d8;
padding-top: 10px;
padding-left: 20px;
padding-right: 20px;
padding-bottom: 10px;
margin-bottom: 10px;
word-wrap: break-word;
min-height: 42px;
}
index.js
var main = function() {
//btnPost
$('#btnPost').click(function() {
var post = $('.status-box').val();
$('<li>').text(post).prependTo('.posts');
$('.status-box').val('');
$('.counter').text('140');
$('#btnPost').addClass('disabled');
});
$('.status-box').keyup(function() {
var postLength = $(this).val().length;
var charactersLeft = 140 - postLength;
$('.counter').text(charactersLeft);
if(charactersLeft < 0) {
$('#btnPost').addClass('disabled');
}
else if(charactersLeft == 140) {
$('#btnPost').addClass('disabled');
}
else {
$('#btnPost').removeClass('disabled');
}
});
$('#btnPost').addClass('disabled');
//btnDelete
$('#btnDelete').click(function(){
});
}
$(document).ready(main);
I have created a fiddle to provide something close to the desired functionality. I'm not sure what you mean by "highlight" the comment, but what you are looking for is event delegation. Using jQuery's .on() function, you can listen for events on dynamically created elements:
$('body').on('click', '.btnDelete', function(){
$(this).closest('li').remove();
});
See this jsFiddle: http://jsfiddle.net/voveson/5gL44z6m/2/
And for more info on how the .on() function works, see here.