To-do list with list item calculation javascript - javascript

So, I've got to make a to-do list purely made from html,css and javascript,problem is, I've barely been taught any javascript at my school and even then,I haven't touched front-end in over a year So I'm quite stumbed here ..
The idea is that there should be an input field where I can add list items to my to-do list and once they're completed,I click on them and they get transfered to a "completed " section while also counting the percentage of how many list items are completed and not completed.
I don't expect anyone to take the time to write out the code(though I would,obviously,appreciate it ),but atleast if I got some direction as to what parts of javascript I should look into,it'd be a great help as is..
<html>
<head>
<title>Site</title>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="true">
<meta charset="UTF-8"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<form>
<div id="myDIV" class="header">
<h2>To-Do</h2>
<input type="text" id='uzd' placeholder="Užduotis">
<input type="button" id='todoadd' >
</div>
</form>
<ul id='uzduotys'>
</ul>
<script src="script.js"></script>
</div>
</body>
</html>
//////javascript
document.getElementById("todoadd").onclick = function() {
var node = document.createElement("Li");
node.setAttribute("id","li");
var text = document.getElementById("uzd").value;
var textnode =document.createTextNode(text);
node.appendChild(textnode);
document.getElementById("uzduotys").appendChild(node);
}
/////////css
body{ background-color: lightgrey; } .container{
margin: 100px 300px;
}
h2{
margin-left: 75px;
font-size: 36px;
color:cornflowerblue;
}
input{
line-height: 30px;
font-size: 20px;
border-radius: 7px;
margin-left: 30px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
background: #eee;
font-size: 25px;
transition: 0.2s;
/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
ul{
margin:20px;
border-radius:15px ;
}
li{
background-color: white;
line-height: 30px;
border-radius:7px;
margin:10px;
}
ul li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}

If you are a student still I hope you take this and learn some more JS. Me as a student starting in CS I was not able to begin to find out what to do. I suggest recognizing the many js tools that there are and growing your knowledge. Try code academy for basic starting help.
<!-- Super basic example with no styling and no counter -->
<html>
<body>
<label>New Item</label>
<input type="text" id="input">
<button id="add">Add New To Do Item</button>
<h1>To Do</h1>
<ul id="toDoList">
</ul>
<h1>Completed</h1>
<ul id="completedList">
</ul>
<script>
//calls when the page loads
(function() {
document.getElementById("add").addEventListener("click", function(){
var newLi = document.createElement("li");
var newDiv = document.createElement("Div");
newDiv.innerText = document.getElementById("input").value;
var newBtn = document.createElement("button");
newBtn.innerText = "Done"
newBtn.addEventListener("click", function(e){
e = e.target || e.srcElement;
//for some reason appending e.parentElement would not work so I had to create a brand new element
var newLi2 = document.createElement("li");
newLi2.innerText = e.parentElement.children[0].innerText;
document.getElementById("completedList").appendChild(newLi2);
e.parentElement.remove();
})
newLi.appendChild(newDiv);
newLi.appendChild(newBtn);
document.getElementById("toDoList").appendChild(newLi);
document.getElementById("input").value = "";
})
})();
</script>
</body>
</html>

Related

Submit button is giving null

I am trying to develop a rating site which is a part of Frontend Mentor Challenge(https://www.frontendmentor.io/challenges/interactive-rating-component-koxpeBUmI) in which I am facing the following problems:-
On clicking submit button it gives a null error. Why is it happening and how can I fix this?
Should I use a modal box for thank you page or is it ok to make a different HTML page to handle the thank you page?
How can I access the 'numbers' class and use it on the 'thank you.html' page?
const numberClicked = document.querySelectorAll(".number")
const submitBtn = document.getElementById("submit-btn")
numberClicked.forEach(function(oneNumbreClicked) {
oneNumbreClicked.addEventListener('click', function() {
console.log(oneNumbreClicked.innerText)
})
})
submitBtn.addEventListener('click', function() {
document.getElementById("final-rating").innerText = `You selected ${oneNumbreClicked.innerText} out of 5`
})
*,
*::after,
*::before {
box-sizing: border-box;
}
body {
font-family: 'Overpass', sans-serif;
background-color: hsl(216, 12%, 8%);
}
.container {
color: white;
width: 35%;
background-color: hsl(213, 19%, 18%);
border-radius: 10px;
box-shadow: 0 10px hsl(216, 12%, 8%);
margin: 3em auto;
padding: 2em;
}
.thank-you-container {
text-align: center;
}
.star {
background-color: hsl(229.4, 14.3%, 23.3%);
border-radius: 50%;
padding: 10px;
}
.numbers {
margin: 0 auto;
}
.number {
display: inline-block;
background-color: hsl(229.4, 14.3%, 23.3%);
border-radius: 50%;
text-align: center;
padding: 10px;
width: 40px;
font-size: 1em;
margin: 0 0.423em;
opacity: 0.5;
border: none;
color: inherit;
}
.submit-btn {
background-color: hsl(25, 97%, 53%);
color: white;
padding: .8em 2em;
width: 100%;
border-radius: 1.5em;
border: none;
margin-top: 1.5em;
font-weight: 400;
font-size: 1.1em;
}
.number:hover {
opacity: 1;
background-color: hsl(217, 12%, 63%);
}
.submit-btn:hover {
opacity: 0.5;
}
.submit-btn:focus,
.number:focus {
opacity: 1;
background-color: white;
color: hsl(25, 97%, 53%);
}
.final-rating {
background-color: hsl(229.4, 14.3%, 23.3%);
color: hsl(25, 97%, 53%);
border-radius: 1.5em;
padding: 0.4em;
margin: 1.3em auto;
width: 12.5em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- displays site properly based on user's device -->
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<link rel="stylesheet" href="style.css">
<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=Overpass:wght#400;700&display=swap" rel="stylesheet">
<title>Frontend Mentor | Interactive rating component | Rating Page</title>
<style>
.attribution {
font-size: 11px;
text-align: center;
color: white;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
</style>
</head>
<body>
<main>
<!-- Rating state start -->
<section class="container">
<img class="star" src="images/icon-star.svg" alt="">
<h2>How did we do?</h2>
<p>
Please let us know how we did with your support request. All feedback is appreciated to help us improve our offering!
</p>
<div class="numbers" id="numbers">
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button class="number">4</button>
<button class="number">5</button>
</div>
<a href="thank.html" target="_self">
<button class="submit-btn" id="submit-btn">Submit</button>
</a>
</section>
<!-- Rating state end -->
<div class="attribution">
Challenge by Frontend Mentor. Coded by Raunak Raj.
</div>
</main>
<script src="script.js"></script>
</body>
</html>
<!--This is the linked HTML file(thank.html) which activates on clicking upon Submit button
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<link rel="stylesheet" href="style.css">
<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=Overpass:wght#400;700&display=swap" rel="stylesheet">
<title>Frontend Mentor | Interactive rating component |Thank You Page</title>
<style>
.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }
</style>
</head>
<body>
<main>
<section class="container thank-you-container">
<img src="images/illustration-thank-you.svg" alt="">
<p class= "final-rating" id="final-rating"></p>
<h2>Thank you!</h2>
<p>We appreciate you taking the time to give a rating. If you ever need more support, don't hesitate to get in touch!</p>
</section>
<div class="attribution">
Challenge by Frontend Mentor.
Coded by Raunak Raj.
</div>
</main>
<script src="script.js"></script>
</body>
</html>
-->
So first it would be better if you could write the whole error, so we have more info of what is causing it.
Issue: But of what I've seen is that, the submit button is wrapped in anchor tags, which is redirecting us to "thank.html" as: <button>Submit</button>, and in the thank.html (the commented code below) you are loading the very same script. <script src="script.js"></script> which causes the problem/error. Why is it causing a problem, is simply because in this script you are accessing the DOM elements which does not exist in thank.html. For example in script.js you access the elements with class query selector .numbers, but when thank.html is loaded this elements are not existing. =)
Solution:
You could create a new unique js file for the purpose of thank.html. And add an event listener on load as: window.addEventListener("load", () => {../logic here}), but with this approach you will have to think of how would you pass the parameter of the value oneNumbreClicked.innerText so you can use and print it. As a starter you could share the information through the sessionStorage or the localeStorage. (There are way more ways)
Other easy and straight forward approach to have only one html file. Have the both <section></section> (section with class container and thank-you-container). Initially the section with class thank-you-container would have css property: display: "none". When clicking on submit button, firstly you will change the display property of the section with class thank-you-container to "flex or block", and change the display prop of the section with class container to "none, and print the text. On a way you will simulate "single page applicaton" :D. And do not forget to remove the <a> </a> tags from the submit button, so you won't redirect.
Dummy demo solution:
const container = document.getElementById("container")
const containerTwo = document.getElementById("thank-you-container")
const myBtn = document.getElementById("myBtn");
myBtn.addEventListener("click", ()=> {
container.style.display = "none";
containerTwo.style.display = "flex";
// your additional logic here
})
.thank-you-container {
display: none}
<div class="container" id="container">
<h1>Container one</h1>
</div>
<div class="thank-you-container" id="thank-you-container">
<h1>Container two</h1>
</div>
<button id="myBtn">Submit</button>

How to prevent content(Tasks) to disappear after REFRESHING

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'));

Why is the CSS Javascript dropdown menu not showing in any browser?

This is the code snippet of the navigational bar I have been trying to make using HTML5, CSS and JavaScript. The Dropdown menu I am attempting to make using CSS and Javascript is similar to the one given as an example in the W3Schools website. This is the code snippet I am using:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable= yes">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="FoodMeets">
<meta name="keywords" content="Restaurants, Bars, Pubs, Cafes, Nightclubs, Hangout places, Hangout zones, Chat forum, Social networking">
<meta name="robots" content="index, follow">
<!--Materialize CSS-->
<link rel="stylesheet" href="styles/materialize.min.css" />
<link rel="stylesheet" href="styles/style.css" />
<!--Normalize CSS-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css" rel="stylesheet" type="text/css">
<!--Google Icons-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<title>FoodMeets</title>
<style>
html,body{
font-family: Georgia, serif;
font-weight: normal;
font-size: 16px;
background-color: #eceff1;
}
nav{
background-color: white;}
nav ul a{
color: #17479e;
font-weight: normal;
}
nav ul a:hover{
text-decoration: none;
}
.nav-wrapper a:hover{
color: #17479e;
text-decoration: none;
}
.icon-design{
position:relative;
top: 4px;
font-size: 20px;
}
.right{
position: relative;
left: -40px;
}
.dropbtn{
display: inline-block;
}
.dropdown {
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.show {display:block;}
</style>
</head>
<body>
<nav class="z-depth-1">
<div class="nav-wrapper">
<img src="images/foodmeets_logo.png" style="position:relative; width:118px; height:69px; top:-2px"/>
<div class="container">
<ul class="left">
<li><span class="material-icons icon-design" aria-hidden="true"></span>Home</li>
<li><span class="material-icons icon-design" aria-hidden="true"></span>Featured</li>
<li><span class="material-icons icon-design" aria-hidden="true"></span>Favorites</li>
</ul>
<ul class="right">
<li><span class="material-icons icon-design"></span>Events & Offers</li>
<li class="dropdown">
Dropdown
<div class="dropdown-content" id="myDropdown">
Link 1
Link 2
Link 3
</div>
</li>
</ul>
</div>
</div>
</nav>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="scripts/materialize.min.js"></script>
<script>
/* When the user clicks on the button, toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
</body>
</html>
This is the result I am getting out of this code:
Navigational Bar
But the Dropdown menu does not seem to work whatever I try to do. I am using Materialize CSS here along with Google Icons.
Can anyone tell me where I am going wrong or is there something wrong with my approach?
Your code should work - as evidence in this fiddle - https://jsfiddle.net/67j1sLkt/
Looks like you need to do some more debugging on your end, because this can be a number of issues. The first 2 that would come to mind are:
Absolute positioning off of the screen. You have your .dropdown-content set to position: absolute, but you have to ask yourself relative to what? I would suggest adding position: relative; to your .dropdown class
z-index. This determines the layers of elements. So it could be that the element is being shown below the background or something.
Some debugging help - if you are in Chrome, I would suggest right clicking on the Dropdown button and select Inspect. Now use your developer tools to highlight your #myDropdown and it should tell you where that element is positioned on the page (if it is shown at that point). You should also check your console for errors to see if that is what the issue is.
works for me
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable= yes">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="FoodMeets">
<meta name="keywords" content="Restaurants, Bars, Pubs, Cafes, Nightclubs, Hangout places, Hangout zones, Chat forum, Social networking">
<meta name="robots" content="index, follow">
<!--Materialize CSS-->
<link rel="stylesheet" href="http://materializecss.com/dist/css/materialize.min.css" />
<link rel="stylesheet" href="styles/style.css" />
<!--Normalize CSS-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css" rel="stylesheet" type="text/css">
<!--Google Icons-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<title>FoodMeets</title>
<style>
html,body{
font-family: Georgia, serif;
font-weight: normal;
font-size: 16px;
background-color: #eceff1;
}
nav{
background-color: white;}
nav ul a{
color: #17479e;
font-weight: normal;
}
nav ul a:hover{
text-decoration: none;
}
.nav-wrapper a:hover{
color: #17479e;
text-decoration: none;
}
.icon-design{
position:relative;
top: 4px;
font-size: 20px;
}
.right{
position: relative;
left: -40px;
}
.dropbtn{
display: inline-block;
}
.dropdown {
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.show {display:block;}
</style>
</head>
<body>
<nav class="z-depth-1">
<div class="nav-wrapper">
<img src="images/foodmeets_logo.png" style="position:relative; width:118px; height:69px; top:-2px"/>
<div class="container">
<ul class="left">
<li><span class="material-icons icon-design" aria-hidden="true"></span>Home</li>
<li><span class="material-icons icon-design" aria-hidden="true"></span>Featured</li>
<li><span class="material-icons icon-design" aria-hidden="true"></span>Favorites</li>
</ul>
<ul class="right">
<li><span class="material-icons icon-design"></span>Events & Offers</li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn" data-activates='myDropdown'>Dropdown</a>
<div class="dropdown-content" id="myDropdown">
Link 1
Link 2
Link 3
</div>
</li>
</ul>
</div>
</div>
</nav>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://materializecss.com/bin/materialize.js"></script>
<script>
/* When the user clicks on the button, toggle between hiding and showing the dropdown content */
/* function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}*/
$('.dropbtn').dropdown({
inDuration: 300,
outDuration: 225,
constrain_width: false, // Does not change width of dropdown to that of the activator
hover: true, // Activate on hover
gutter: 0, // Spacing from edge
belowOrigin: false, // Displays dropdown below the button
alignment: 'left' // Displays dropdown with edge aligned to the left of button
}
);
</script>
</body>
</html>
$(document).ready(function() {
function myFunction(){
$(".dropbtn").click(function() {
$("#myDropdown").toggle();
});
}
this much is fulfill your requirement

How can I update local html file after adding new element using javascript?

I am new to web development.
I am try to add a list item to a unorded list.
using javascript
html
<!DOCTYPE html>
<html>
<head>
<title>Item Add Test</title>
<script src="item.js"></script>
<link rel="stylesheet" type="text/css" href="item.css">
</head>
<body>
<input type="text" id="initem"></input>
<br /><br />
<button onclick="myFunction1()" id="submit">SUBMIT</button>
<ul id="menu">
<li>ABC</li>
<li>BLA</li>
</ul>
</body>
</html>
css item.css
body {
font-family: monospace;
text-align: center;
font-size: 1.5em;
}
input {
text-align: center;
width: 300px;
height: 30px;
border: 1px solid blue;
border-radius: 5px;
margin: 10px auto;
padding-left: 10px;
font-size: 1.2em;
font-weight: bold;
}
#submit {
font-size: 1em;
}
javascript item.js
function myFunction1() {
var name = document.getElementById("initem").value;
var node = document.createElement("LI");
var textnode = document.createTextNode(name);
node.appendChild(textnode);
document.getElementById("menu").appendChild(node);
}
I successfully add items to the list.
But when I refresh the page all items are gone.
How can I save the html file or update the html file after adding the items,so that if I refresh the page list items remain there.
You can save the text of <li> elements in the local storage and retrieve on load event of the body.
The snippet won't work for security reasons but I tried on Sublime Text and it's fine.
var li_texts = [];
function myFunction1() {
var name = document.getElementById("initem").value;
var node = document.createElement("LI");
var text = 'Test';
node.innerHTML = text;
document.getElementById("menu").appendChild(node);
li_texts.push(text);
localStorage.setItem("li_texts", JSON.stringify(li_texts));
}
function loadList(){
if (localStorage.getItem("li_texts") !== null) {
var stored_names = JSON.parse(localStorage.getItem("li_texts"));
for(i=0; i<stored_names.length; i++){
var node = document.createElement("LI");
node.innerHTML = stored_names[i];
document.getElementById("menu").appendChild(node);
}
}
else{
return;
}
}
body {
font-family: monospace;
text-align: center;
font-size: 1.5em;
}
input {
text-align: center;
width: 300px;
height: 30px;
border: 1px solid blue;
border-radius: 5px;
margin: 10px auto;
padding-left: 10px;
font-size: 1.2em;
font-weight: bold;
}
#submit {
font-size: 1em;
}
<!DOCTYPE html>
<html>
<head>
<title>Item Add Test</title>
<script src="item.js"></script>
<link rel="stylesheet" type="text/css" href="item.css">
</head>
<body onload="loadList()">
<input type="text" id="initem"></input>
<br /><br />
<button onclick="myFunction1()" id="submit">SUBMIT</button>
<ul id="menu">
<li>ABC</li>
<li>BLA</li>
</ul>
</body>
</html>

how to count how many elements have a certain class

I am using jQuery to try and find which IDs have a certain class name. The reason this is important to me is I am using toggleClass() from jQuery to show and hide certain divs and when a button is selected I want a viewport to display or hide. I have 2 personal goals: One is to find a way to do this in jquery and the other is to understand how to do this in javascript. I understand the javascript will be much more advanced and I am prepared.
How can I use the resetViewport() to count the amount of "selected" classes?
Is there a better way to do this?
In javascript, how can one do this same thing? Even if you tell me specific methods in js thats ok. I am not asking for exact code. I just want to learn.
Just so there is no question I added the code. Lets start by looking at my personal hosted web page called CodeAmend and here is the code
****html***
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Player</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<p>CodePlayer</p>
<nav>
<ul>
<li id="html-button" class="toggle selected no-highlight">HTML</li>
<li id="css-button" class="toggle selected no-highlight">CSS</li>
<li id="js-button" class="toggle selected no-highlight">JS</li>
<li id="result-button" class="toggle selected no-highlight">Result</li>
</ul>
</nav>
<div id="run-button" class="no-select">Run</div>
</div>
<div id="html-container" class="code-container">
<div class="code-label">HTML</div>
<textarea>Code</textarea>
</div>
<div id="css-container" class="code-container">
<div class="code-label">CSS</div>
<textarea>Code</textarea>
</div>
<div id="js-container" class="code-container">
<div class="code-label">JS</div>
<textarea>Code</textarea>
</div>
<div id="result-container" class="code-container">
<div class="code-label">Result</div>
<iframe>Code</iframe>
</div>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
* here is javascript / jquery *
$("[id^=button]").click(function () {
$(this).toggleClass('selected');
// creates the name of a viewport ID. "view-" + html of button
var viewID = "#view-" + $(this).html();
$(viewID).toggle();
resetViewport(4);
});
function resetViewport(numberOfViewports) {
var viewSize;
switch (numberOfViewports) {
case 1:
viewSize = "400px";
break;
case 2:
viewSize = "198px";
break;
case 3:
viewSize = "131px";
break;
case 4:
viewSize = "98px";
break;
}
$("[id^=view]").css("width", viewSize);
}
here is css
* {
margin: 0;
padding: 0;
}
body {
font-size: 14px;
}
.clear-fix {
clear: both;
}
.no-highlight {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* why does menu margin excape parent without padding on container.. change to 0 and all margen excapes. */
#container {
width: 400px;
height: 456px;
margin: 0 auto;
padding-top: 1px;
background-color: #555;
border-radius: 5px;
}
/* Menu styling */
#menu {
width: 231px;
margin: 10px auto;
}
#menu li {
width: 50px;
height: 30px;
border: 2px solid #58d;
border-radius: 10px;
background-color: #000;
color: #333;
line-height: 30px;
text-align: center;
font-size: .8em;
text-transform: uppercase;
list-style: none;
float: left;
cursor: pointer;
}
#menu li+li {
margin-left: 5px;
}
#menu .selected {
background-color: #fff;
color: #333;
font-weight: bold;
}
[id^="view"] {
width: 98px;
height: 400px;
margin: 1px;
float: left;
background-color: #ddd;
}
jQuery collections and Javascript NodeLists are both array-like, so you can use the .length property to get the number of elements.
jQuery:
resetViewport($(".selected").length);
Plain Javascript:
resetViewport(document.getElementsByClassName("selected").length);

Categories